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条)

报告相同问题?

悬赏问题

  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容