我有这样的 table
id | item_id | item_key | item_value
------------------------------------
1 | 5 | rating | 6.4
2 | 5 | country | US
3 | 6 | rating | 7.4
4 | 6 | country | UK
5 | 7 | rating | 6.5
6 | 7 | country | US
7 | 8 | rating | 7.9
8 | 8 | country | UK
9 | 5 | genre | Action
10| 5 | year | 2019
11| 6 | genre | Drama
12| 7 | lang | EN
我想选择 item_id,其中 country = US 且评分不为空,然后按评分排序
EDITED : and ability to check another item_key's values like "genre = 'drama' and year = '2019'" etc
i have more than 10 item_key's variables not only rating and country but if know the method i'll apply for the others
我是这样制作的,它可以工作,但我的问题是按评分排序
$sql = "SELECT metas.* FROM metas ";
if ($cat)
$sql .= "LEFT JOIN articles ON metas.item_id = articles.id ";
$sql .= "GROUP BY metas.item_id HAVING (sum(metas.meta_key = 'rating' AND metas.meta_value != '' AND metas.item_type = '1') AND ";
foreach ($filters as $filter_key => $filter_val){
if (!empty($filter_val)){
if (array_key_exists($filter_val, ${'m_'.$filter_key.'s'})){
if ($filter_key == "genre")
$sql .= (($counter == 1) ? "" : "AND ")."sum(".($cat ? "articles.category = '".$cat."' AND " : "") ."metas.meta_key = '".$filter_key."' AND metas.meta_value LIKE '%".$filter_val."%') ";
else
$sql .= (($counter == 1) ? "" : "AND ")."sum(".($cat ? "articles.category = '".$cat."' AND " : "") ."metas.meta_key = '".$filter_key."' AND metas.meta_value = '".$filter_val."') ";
$trusted_filters[$filter_key] = $filter_val;
$counter++;
} else {
$errs++;
}
}
}
$sql .= ") ORDER BY FIELD(metas.meta_key, 'rating') DESC, metas.meta_value DESC";
就像我说的,它可以工作,但不能工作,我需要根据带有评分值的 item_key 按 item_value 对它进行排序。
最佳答案
您不需要为要添加的每个条件都将表与其自身连接。您正在寻找 PIVOT。
模式(MySQL v5.7)
CREATE TABLE metas (
`id` INT(11) AUTO_INCREMENT,
`item_id` INT(11),
`item_key` VARCHAR(255),
`item_value` VARCHAR(255),
PRIMARY KEY (`id`)
);
INSERT INTO metas
(`item_id`, `item_key`, `item_value`)
VALUES
(5, 'rating', '6.4'),
(5, 'country', 'US'),
(6, 'rating', '7.4'),
(6, 'country', 'UK'),
(7, 'rating', '6.5'),
(7, 'country', 'US'),
(8, 'rating', '7.9'),
(8, 'country', 'UK'),
(5, 'genre', 'Action'),
(5, 'year', '2019'),
(6, 'genre', 'Drama'),
(7, 'lang', 'EN');
查询#1
SELECT item_id,
MAX(IF(item_key = 'rating', item_value, NULL)) AS rating
FROM metas
GROUP BY item_id
HAVING MAX(IF(item_key = 'country', item_value, NULL)) = 'US',
AND MAX(IF(item_key = 'genre', item_value, NULL)) = 'Action'
AND MAX(IF(item_key = 'year', item_value, NULL)) = '2019'
ORDER BY rating DESC;
输出:
| item_id | rating |
| ------- | ------ |
| 5 | 6.4 |
使用 GROUP BY 后,您可以组装“行的集群”或“聚合数据”。您必须筛选聚合数据以隔离具有相应键的行以仅保留该值(所有其他行将暂时变为该表达式中的 NULL
)。
或者只是 item_id,像这样:https://www.db-fiddle.com/f/tWWfSRDyXv36ZRevRivj5B/1
关于php - 为同一列选择多个条件并排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59494217/