我有两张桌子:
帖子
+--------------------------------------------------------------------+
|id ¦status¦type ¦url |
+------------+------+-----+------------------------------------------+
|25949664 ¦80 ¦link ¦http://example.com/25949664 |
|25777570 ¦80 ¦photo¦http://example.com/25777570 |
+--------------------------------------------------------------------+
属性
╔════════════╦════════════╦══════════════════════════════════════════╗
║id ║attr ║value ║
╠════════════╬════════════╬══════════════════════════════════════════╣
║25949664 ║timestamp ║1430836105 ║
║25949664 ║tag ║red ║
║25949664 ║tag ║yellow ║
║25949664 ║tag ║brown ║
║25949664 ║source ║http://example.com/wallin/ ║
║25949664 ║source_title║wallin ║
║25949664 ║state ║published ║
║25949664 ║format ║html ║
║25777570 ║timestamp ║1430836105 ║
║25777570 ║tag ║red ║
║25777570 ║tag ║yellow ║
║25777570 ║tag ║brown ║
║25777570 ║tag ║black ║
║25777570 ║tag ║orange ║
╚════════════╩════════════╩══════════════════════════════════════════╝
执行此查询:
SELECT posts.id, GROUP_CONCAT(attributes.value) as tags
FROM posts
JOIN attributes ON attributes.id = posts.id
WHERE ( attributes.attr = 'tag' )
AND ( attributes.value IN ('red','brown') )
GROUP BY posts.id
HAVING COUNT(DISTINCT attributes.value) = 2
我有这个结果:
╔════════════╦════════════╗
║id ║tags ║
╠════════════╬════════════╣
║25949664 ║red,brown ║
║25777570 ║red,brown ║
╚════════════╩════════════╝
我宁愿拥有这个:
╔════════════╦════════════════════════════════╗
║id ║tags ║
╠════════════╬════════════════════════════════╣
║25949664 ║red,yellow,brown ║
║25777570 ║red,yellow,brown,black,orange ║
╚════════════╩════════════════════════════════╝
实际上,拥有 n 标记后,我会检索只执行一次查询的所有帖子标记。
任何人都有建议,或者这完全不可能?
答案 0 :(得分:1)
SELECT posts.id, GROUP_CONCAT(attributes.value) as tags
FROM posts
JOIN attributes ON attributes.id = posts.id
WHERE ( attributes.attr = 'tag' )
AND ( attributes.value IN ('red','brown') )
GROUP BY posts.id
使用和条件,仅获取红色和棕色属性。因此,您需要删除此条件并重写该条件。
我认为这可以帮到你:
SELECT posts.id, GROUP_CONCAT(attributes.value) as tags
FROM posts
JOIN attributes ON attributes.id = posts.id
WHERE ( attributes.attr = 'tag' )
GROUP BY posts.id
HAVING Find_In_Set('red',tags)>0 AND Find_In_Set('brown',tags)>0