dongshou6041 2015-02-04 10:57
浏览 240
已采纳

MySQL SELECT语句,其中value在数组中

I need some help with an MySQL statement that I cannot really make to work.

I have a table like this:

+---+-------------------------------+
|id | fruit                         |
+---+-------------------------------+
| 1 | apple,orange,pear,grape,lemon |
| 2 | pear,melon,apple,kiwi,lemon   |
| 3 | orange,kiwi,pear,apple,cherry |
| 4 | grape,lemon,cherry,apple,melon|
+---+-------------------------------+

What I need to do is to SELECT all rows where the column fruit contains the word melon. The word in question might be at any position in the array.

I tired with the below query but for some reason I only get 3-4 rows, definitely not all of them:

$fruit = $_GET['fruit'];
$query1= "SELECT * FROM tbl_fruits WHERE ".$fruit." IN (fruit)";

Any comments will be appreciated.

  • 写回答

6条回答 默认 最新

  • douying7289 2015-02-04 10:59
    关注

    You can use FIND_IN_SET

    SELECT * FROM tbl_fruits 
    WHERE find_in_set('$fruit', fruit)
    

    But you actually should rather change your table design.

    Never store multiple values in a single column!

    A better table design would be

    fruits table
    ------------
    id    name
    1     melon
    2     orange
    3     apple
    ...
    
    
    products table
    -------------------
    id    name   price
    1     P1     1.50
    2     P2     2.99
    3     P3     0.99
    
    
    product_fruits table
    --------------------
    product_id   fruit_id
    1            1
    1            2
    2            2
    3            1
    

    That is a classic many to many relation (m to n).

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(5条)

报告相同问题?

悬赏问题

  • ¥30 vmware exsi重置后的密码
  • ¥15 易盾点选的cb参数怎么解啊
  • ¥15 MATLAB运行显示错误,如何解决?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容
  • ¥15 关于#stm32#的问题:CANOpen的PDO同步传输问题
  • ¥20 yolov5自定义Prune报错,如何解决?
  • ¥15 电磁场的matlab仿真
  • ¥15 mars2d在vue3中的引入问题
  • ¥50 h5唤醒支付宝并跳转至向小荷包转账界面