[英]mysql: select from a table where key is equal to a value and also select all the rows related to that value directly or indirectly
[英]Select rows where all criteria matches from a key value table
我有以下查詢:
select *
from user_interests
join interests using(interest_id)
where tag in('running', 'biking')
and user_id != 1;
注意: in()
值是使用php動態生成的,因此它們可以是一個值或100個值,每個值都通過用戶瀏覽器$_GET
傳入。
我的user_interests表非常簡單,因為它只是interest_id
和user_id
的列表。
CREATE TABLE `user_interests` (
`interest_id` INT(10) UNSIGNED NOT NULL,
`user_id` INT(10) UNSIGNED NOT NULL,
PRIMARY KEY (`interest_id`, `user_id`)
);
我的興趣表是一個簡單的表,其中包含不同類型的興趣( running
, biking
等)的列表
CREATE TABLE `interests` (
`interest_id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
`tag` VARCHAR(50) NOT NULL,
`category_id` TINYINT(3) UNSIGNED NOT NULL,
PRIMARY KEY (`interest_id`),
UNIQUE INDEX `tag` (`tag`)
);
由於每個用戶都有很多興趣,因此我如何在數據庫中搜索具有列表中所有興趣的用戶。 對於上面的查詢,它將running
和biking
。 我的查詢僅使具有至少一種以上條件的人獲得,如何使之具有所有被查詢興趣的用戶?
因此,如果用戶有5個興趣,並且我傳入2,並且他們的5列表中有2個興趣,則應返回其個人資料。 如果他們只傳遞了2個配置文件中的1個,則不應返回該配置文件。
我會嘗試的
SELECT *
FROM user_interests
WHERE user_interests.user_id IN (
SELECT ui.user_id
FROM user_interests ui
left join interests i using(interest_id)
WHERE i.tag IN ($php_array)
^ PHP
and ui.user_id != 1
GROUP BY ui.user_id
HAVING COUNT(i.tag) >= count($php_array)
^ PHP
)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.