通过比较2个表值来选择查询

时间:2020-04-10 10:06:35

标签: mysql select

我有2个表(tbl_news和tbl_news_category) tbl_news_category表是

cat_id  cat_name   general
1       name1       1
2       name2       1
3       name3       0
4       name4       1
5       name5       0

tbl_news表是

id    cat_id    title     news_isimage
1       2       title1      1
2       5       title2      0
3       1       title2      1
4       3       title2      1
5       2       title2      1
6       5       title2      1
7       4       title2      1
8       5       title2      1

我想从tbl_news中获得5个随机项目,其一般值应为1 我尝试了下面的代码,但无法正常工作

SELECT 
    d.*
FROM
    tbl_news d,
    tbl_news_category p
WHERE
    p.general = 1 AND d.news_isimage = 0
        AND d.cat_id > 3
ORDER BY RAND()
LIMIT 5

但其提供的新闻项是cat_id,Gen​​eral = 0

2 个答案:

答案 0 :(得分:1)

对表进行正确的连接:

select n.* 
from tbl_news n inner join tbl_news_category c
on c.cat_id = n.cat_id
where c.general = 1
order by rand() limit 5

您的代码中还具有以下条件:

news_isimage = 0 AND cat_id > 3

如果需要它们,可以将它们添加到WHERE子句中:

WHERE c.general = 1 AND n.news_isimage = 0 AND c.cat_id > 3

答案 1 :(得分:0)

没有可用的查询数据。

但是要进行内部联接

CREATE TABLE tbl_news (
  `id` INTEGER,
  `cat_id` INTEGER,
  `title` VARCHAR(6),
  `news_isimage` INTEGER
);

INSERT INTO tbl_news
  (`id`, `cat_id`, `title`, `news_isimage`)
VALUES
  ('1', '2', 'title1', '1'),
  ('2', '5', 'title2', '0'),
  ('3', '1', 'title2', '1'),
  ('4', '3', 'title2', '1'),
  ('5', '2', 'title2', '1'),
  ('6', '5', 'title2', '1'),
  ('7', '4', 'title2', '1'),
  ('8', '5', 'title2', '1');

CREATE TABLE tbl_news_category (
  `cat_id` INTEGER,
  `cat_name` VARCHAR(5),
  `general` INTEGER
);

INSERT INTO tbl_news_category
  (`cat_id`, `cat_name`, `general`)
VALUES
  ('1', 'name1', '1'),
  ('2', 'name2', '1'),
  ('3', 'name3', '0'),
  ('4', 'name4', '1'),
  ('5', 'name5', '0');
✓

✓

✓

✓
SELECT 
    tn.title
    , tn.news_isimage
    ,tnc.cat_name
FROM tbl_news tn INNER JOIN tbl_news_category tnc ON tn.cat_id = tnc.cat_id 
WHERE
    tnc.general = 1 
    AND tn.news_isimage = 0
    AND tnc.cat_id > 3
ORDER BY RAND()
LIMIT 5
title | news_isimage | cat_name
:---- | -----------: | :-------

db <>提琴here