简体   繁体   English

mysql 多对多查询与来自另一个表的位置

[英]mysql many-to-many query with where from another table

This should be trivial, but my SQL chops are still pretty weak.这应该是微不足道的,但我的 SQL 排版仍然很弱。 I have setup an intermediate table for many-to-many queries in MySQL, let's call it 'item_packs' linking the 'packs' table with the 'items' table.我已经为 MySQL 中的多对多查询设置了一个中间表,我们称之为“item_packs”,将“packs”表与“items”表链接起来。 I want to list all the 'items' where the entered 'pack_name' matches the name in the 'packs' table.我想列出所有输入的“pack_name”与“packs”表中的名称相匹配的“items”。

packs table

packindex | packname (varchar) ------------------------------ 1 | todayspack 2 | anotherpack

items table

itemindex | itemname (varchar) ------------------------------ 1 | firstitem 2 | anotheritem

item_packs table

item | pack ------------------------------ 1 | 2 2 | 2

I almost have it:我几乎拥有它:

SELECT c.*
FROM items c
JOIN item_packs j on j.item = c.itemindex
JOIN packs t on j.pack = t.packindex
where  j.pack= 1

It works if I enter the pack index (1) but I need to have that value come from the index in the 'packs' table where the pack name matches the entered pack name (todayspack).如果我输入包索引 (1),它会起作用,但我需要让该值来自“包”表中的索引,其中包名称与输入的包名称 (todayspack) 匹配。

So you want to compare the name to some string?所以您想将名称与某个字符串进行比较? Your query looks good, try this:您的查询看起来不错,试试这个:

SELECT c.*
FROM items c
JOIN item_packs j on j.item = c.itemindex
JOIN packs t on j.pack = t.packindex
where  j.packname='todayspack'
SELECT c.*
FROM items c
JOIN item_packs j on j.item = c.itemindex
JOIN packs t on j.pack = t.packindex
where  t.packname = 'todayspack';

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM