简体   繁体   中英

PostgreSQL query with the data from the references table

I have two tables:

items

------------------
| item_id | text |
------------------

CREATE TABLE items (
item_id varchar PRIMARY KEY,
text varchar
);

activity

------------------------
| message_id | item_id |
------------------------

CREATE TABLE activity (
message_id varchar PRIMARY KEY,
item_id varchar not null references items(item_id)
);

How to correctly make a query with the data from the items table? I need to find by value message_id or item_id

I tried:

select * from items, activity where items.item_id = activity.item_id and activity.item_id = 'it123';

select * from activity, items where activity.item_id = items.item_id and 'activity.item_id' = 'it123';

This true query:

SELECT * FROM items JOIN activity ON items.item_id = activity.item_id;

And this true query:

SELECT * FROM activity WHERE item_id = 'ea02ea57ff1b';

You need a table JOIN . So you could do something like:

SELECT * FROM items 
   JOIN activity ON items.item_id = activity.item_id
   WHERE items.item_id = 'it123';

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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