内部联接以从子表中的外键获取“名称”属性

时间:2018-09-20 20:35:49

标签: mysql join

我有下表:

CREATE TABLE lookup.cart
(
    id int(10) unsigned PRIMARY KEY NOT NULL AUTO_INCREMENT,
    name varchar(100) NOT NULL
);

CREATE TABLE lookup.it_tags
(
    id int(10) unsigned PRIMARY KEY NOT NULL AUTO_INCREMENT,
    cart_id int(10) unsigned NOT NULL,
    it_tag varchar(25) NOT NULL,
    CONSTRAINT it_tags_ibfk_1 FOREIGN KEY (cart_id) REFERENCES lookup.cart (id) ON DELETE CASCADE
);
CREATE INDEX pn_cart_index ON lookup.it_tags (cart_id);

diagram

我想做的是从IT_Tag表中搜索IT_TAGS上的数据库,并根据存储在it_tags中的密钥以基于的购物车名称返回。名称属性在cart.name中。

假设我的表设置正确,什么是正确的(假设再次)内部联接返回所需的数据?

2 个答案:

答案 0 :(得分:2)

如果我了解您的需求,可以查询

SELECT c.name
FROM cart c
INNER JOIN it_tags t ON c.id = t.cart_id
WHERE it_tag = <what you need>

自然地,搜索部分可能不同于等于。
您可能需要LIKE运算符或其他...

答案 1 :(得分:1)

结果可以通过多个查询

JOIN With WHERE子句

SELECT 
 *
FROM 
 cart 
INNER JOIN 
 it_cart 
ON
 cart.id = it_cart.cart_id
WHERE
  it_cart.it_tag = 'tag'

JOIN不带WHERE子句

SELECT 
 *
FROM 
 cart 
INNER JOIN 
 it_cart 
ON
     cart.id = it_cart.cart_id
  AND
     it_cart.it_tag = 'tag'

已交付表/子查询的JOIN方法

SELECT
 *
FROM (
      SELECT
         cart_id
       FROM
         it_cart 
       WHERE
         it_cart.it_tag = 'tag'

) AS it_cart 
INNER JOIN
 cart
ON
 it_cart.cart_id = cart.id

使用IN运算符

SELECT 
 *
FROM 
 cart 
WHERE
 cart.id IN (
   SELECT
     cart_id
   FROM
     it_cart 
   WHERE
     it_cart.it_tag = 'tag'
)

仅适用于AS MySQL 8.0+的公用表表达式

WITH it_cart_cte AS (
  SELECT
     cart_id
   FROM
     it_cart 
   WHERE
     it_cart.it_tag = 'tag'
)
SELECT 
 *
FROM 
 cart 
JOIN 
 it_cart_cte 
ON
 cart.id = it_cart.cart_id
相关问题