duanliaozhi2915 2013-01-27 18:16
浏览 70
已采纳

匹配MySQL查询中的数组值

I will illustrate my question with a fruit example:

I have an array with some values of fruit_type id's.

$match= array("1","5","8").

I have a cell (fruit_type) in the table 'fruit'. The value of this cell is like this: "1,3,9". It contains all the fruit_type id's that belong to this row.

Now I want to make my SELECT query to return all the rows that have any, a combination of all of the id's 1,5 or 8.

This query won't work, because this will only work if the cell value is '1,5,8' and not 1 or 5 or 8 (or a combination or all of them):

SELECT * FROM fruit WHERE fruit_type IN ('".implode("','",$match)."')

Any ideas?

EDIT (I think the question wasn't clear enough.. So what I would like in this example is: A query that will match ANY of the (cell) value's 1 or 3 or 9 with ANY of the value's from $match (1 or 5 or 8).

  • 写回答

2条回答 默认 最新

  • dotn30471 2013-01-28 08:31
    关注

    The problem doesn't lie in the query, but in the DB structure. You shouldn't put multiple IDs in a single column (at least not if you want to query on it). You can get it to work, but it will always be very slow.

    Instead of the column fruit_type, you should have a table fruit_type.

    CREATE TABLE fruit_fruittype (fruit_id INT, fruit_type_id INT, PRIMARY KEY (`fruit_id`,`fruit_type_id`));
    

    Add a row for each fruit type per fruit.

    Now you easily query the fruits for types:

    SELECT fruit.* FROM fruit INNER JOIN fruit_fruittype ON fruit.id = fruit_fruittype.fruit_id WHERE fruit_type_id IN (1, 5, 8) GROUP BY fruit.id;
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)
  • ¥50 mac mini外接显示器 画质字体模糊
  • ¥15 TLS1.2协议通信解密
  • ¥40 图书信息管理系统程序编写
  • ¥20 Qcustomplot缩小曲线形状问题
  • ¥15 企业资源规划ERP沙盘模拟