SELECT issue in MySQL - mysql

I am trying to perform a SELECT but I am not able to retrieve the data I want.
I have tried lots of sentences without success, so that's why I am exposing here the whole problem.
Here is my database (four tables):
-- Table users
CREATE TABLE users (
user_id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
device_id VARCHAR(15),
private_user_id VARCHAR(16),
public_user_id VARCHAR(16)
);
-- Table events
CREATE TABLE events (
event_id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
public_event_id VARCHAR(8),
ref_user_id INT NOT NULL REFERENCES users(user_id),
name VARCHAR(64),
description VARCHAR(256)
);
-- Table proposals
CREATE TABLE proposals (
proposal_id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
public_proposal_id VARCHAR(8),
ref_event_id INT NOT NULL REFERENCES events(event_id),
proposal_date VARCHAR(32),
proposal_location VARCHAR(64),
proposal_type INT
);
-- Table responses
CREATE TABLE responses (
response_id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
ref_user_id INT NOT NULL REFERENCES users(user_id),
ref_proposal_id INT NOT NULL REFERENCES proposals(proposal_id),
user_name VARCHAR(32),
response INT
);
There are users. There are events. Events are created by one user. Events have proposals. Proposals have responses from the users. I need:
I need to achieve this given a private user id. Is something like: given
the private user id, analyze the responses of that user, so analyze
the proposals of that responses, and finally get the events of that
responses, RETURNING THE PUBLIC USER ID of the creator of each event.
I have tried with:
SELECT DISTINCT events.ref_user_id, public_event_id, name, description, public_user_id
FROM events, users, proposals, responses
WHERE responses.ref_user_id = user_id
AND private_user_id = 'lk0X3lOQl972U7pB'
but the public_user_id retrieved is the user that has responded, while I need the event creator.

SELECT ALL -- show all
u.pulic_user_id AS creator_pulic_user_id, -- creators' public IDs
e.name AS event_name -- and events' names
FROM -- from
events AS e -- events
JOIN -- and
users AS u -- their creator
ON e.ref_user_id = u.user_id
WHERE -- where
EXISTS -- exists
( SELECT 1 -- a
FROM responses AS r -- response
JOIN users AS ur -- by a user,
ON ur.user_id = r.ref_user_id
JOIN proposals AS p -- for a proposal
ON p.proposal_id = r.ref_proposal_id
WHERE p.ref_event_id = e.event_id -- that is about that event
AND ur.private_user_id = #X -- and the responding user
) ; -- has private ID = #X
Sidenote: Inline foreign key constraints, like this:
ref_user_id INT NOT NULL REFERENCES users(user_id),
are parsed (only for syntax correctness) and ignored in MySQL. You have to add them in the end of a CREATE TABLE statement to be valid and enforced. Or use ALTER TABLE, if you have already inserted data in the tables.

If it's just the ids that are wrong it's because you're returning public_user_id from the user table, you want events.ref_user_id, try this:
SELECT DISTINCT events.ref_user_id AS public_user_id , public_event_id, name, description
FROM events, users, proposals, responses
WHERE (responses.ref_user_id = user_id
AND ref_proposal_id = proposal_id AND ref_event_id = event_id)
Edit
I think this is what you want:
SELECT DISTINCT e.ref_user_id AS public_user_id
FROM events e, users u, proposals p, responses r
WHERE r.ref_user_id = u.user_id
AND r.ref_proposal_id = p.proposal_id
AND p.ref_event_id = e.event_id
AND u.private_user_id = 'lk0X3lOQl972U7pB'
;

Related

How to get the user with most comments from a table

I am trying to get the user first name with the most comments. How can I do this?
Here are the tables.
The tables below are the setup for the database tables which I am trying to query.
CREATE TABLE User(
userid varchar(3),
firstname varchar(20),
lastname varchar(20),
age int,
PRIMARY KEY(userid)
)ENGINE=INNODB;
CREATE TABLE Comment(
commentid varchar(3),
userid varchar(3),
eventid varchar(3),
title varchar(20),
comment varchar(50),
PRIMARY KEY(commentid),
FOREIGN KEY(userid) REFERENCES AnonymousUser(userid),
FOREIGN KEY(eventid) REFERENCES Event(eventid)
)ENGINE=INNODB;
INSERT INTO User VALUES('U01','Charles','Darwin',99);
INSERT INTO User VALUES('U02','Keisha','Strawn',24);
INSERT INTO User VALUES('U03','Denise','Malcolm',59);
INSERT INTO User VALUES('U04','Dennis','Stewart',19);
INSERT INTO User VALUES('U05','Robert','Johns',45);
INSERT INTO User VALUES('U06','Marsha','Stewart',33);
INSERT INTO Comment VALUES ('C01','A01','E01','Boring Event','This event was boring');
INSERT INTO Comment VALUES ('C02','A02','E01','Nice Nice Event','This event was Nice');
INSERT INTO Comment VALUES ('C03','A03','E03','Wow','This event was Amazing');
INSERT INTO Comment VALUES ('C04','A01','E01','Very Sad','I missed this event');
The query I tried is
SELECT User.userid FROM User
JOIN comment ON comment.userid = user.userid
WHERE (SELECT COUNT(comment)
FROM comment = (SELECT MAX(userid) FROM comment);
SELECT
userid
FROM
comment
GROUP BY userid
ORDER BY count(userid) DESC
LIMIT 1;
Edit: oh, you need the username. Try this:
SELECT firstname
FROM user
WHERE userid = (
SELECT
userid
FROM
comment
GROUP BY userid
ORDER BY count(userid) DESC
LIMIT 1
);
Query to get firstname with most comments is
select a.firstname, max(a.comment_count) from (
select u.firstname, count(c.commentid) comment_count
from user u join comment c on u.userid = c.userid
group by u.firstname
)a;
That said, I noticed
One of the constraints on table 'comment' is pointing to a table 'AnonymousUser' FOREIGN KEY(userid) REFERENCES AnonymousUser(userid). You have not shared the create table statement for that table.
I had to remove this constraint from table definition in order to successfully create this table in my database
CREATE TABLE Comment(
commentid varchar(3),
userid varchar(3),
eventid varchar(3),
title varchar(20),
comment varchar(50),
PRIMARY KEY(commentid)
);
You dataset for table 'comment' has no userid matching 'user.userid' values
I updated the 'comment' table inserts so I could get some result when executing my query.
INSERT INTO Comment VALUES ('C01','U01','E01','Boring Event','This event was boring');
INSERT INTO Comment VALUES ('C02','U01','E01','Nice Nice Event','This event was Nice');
INSERT INTO Comment VALUES ('C03','U03','E03','Wow','This event was Amazing');
INSERT INTO Comment VALUES ('C04','U06','E01','Very Sad','I missed this event');

Trying to find 3 columns from 3 different tables

I have the following 3 tables:
CREATE TABLE Pins (
email varchar(100) NOT NULL,
boardID int NOT NULL,
));
CREATE TABLE Boarders (
email varchar(100) NOT NULL,
boardID int NOT NULL,
FOREIGN KEY (categoryName) REFERENCES Category (name));
CREATE TABLE User (
email varchar(100) NOT NULL,
name varchar(50),
PRIMARY KEY (email));
I am wanting to make the query search results this: for each Pin, show the description
This obviously is not working, but any suggestions on how to get the above to display?
select p.description ,c.title, u.name from PushPin p,CorkBoard c, User u
where c.email=u.email and c.email =p.email and c.boardID = p.boardID
order by p.description
Yes, this will require you to join the three tables.
Something like the below code should work.
Just defining the Foreign key relations does not mean you would not need to join while querying.
SELECT PP.description, CB.title, U.name
FROM PushPin PP JOIN CorkBoard CB ON PP.boardID = CB.boardID
JOIN USSER U ON PP.email = U.email
WHERE description like '$search'
ORDER BY description;

Function .JSON_OBJECT does not exist

I have 2 tables and I try to get statuses from table status and add to each status info about an author from a user table. I created the same database on my laptop and everything works fine. But I've got an error when published the database on Heroku using ClearDB:
[42000][1305] FUNCTION heroku_1ecaeb2cbfaf113.JSON_OBJECT does not exist
Without JSON_OBJECT query works fine. What's going on? Where I made a mistake?
My tables:
CREATE TABLE IF NOT EXISTS user (
login VARCHAR(15) NOT NULL PRIMARY KEY,
name VARCHAR(15),
avatar VARCHAR(150),
ts INT,
hash BINARY(60)
);
CREATE TABLE IF NOT EXISTS status (
id INT UNSIGNED NOT NULL PRIMARY KEY AUTO_INCREMENT,
note VARCHAR(300),
author VARCHAR(15),
ts INT,
replyTo INT UNSIGNED
);
My query:
SELECT
status.id,
status.note,
status.ts,
JSON_OBJECT(
'login', statusAuthor.login,
'name', statusAuthor.name
)
FROM
user,
user statusAuthor
INNER JOIN status ON statusAuthor.login = status.author
WHERE
user.login = 'some_user' AND status.replyTo IS NULL
ORDER BY status.id
DESC
LIMIT 11;

Selecting a default value if an entry doesn't exist

I have three tables...users, user_info, and quota_levels. They look like this:
CREATE TABLE users (
id INT NOT NULL AUTO_INCREMENT,
name VARCHAR(31) NOT NULL,
password VARCHAR(33) NOT NULL,
PRIMARY KEY (id)
);
CREATE TABLE user_info (
userID INT UNSIGNED NOT NULL,
firstName VARCHAR(32),
lastName VARCHAR(32),
phone CHAR(14),
address VARCHAR(128),
birthdate DATE,
misc TEXT,
quotaLevel VARCHAR(32),
PRIMARY KEY (userID)
);
CREATE TABLE quota_levels (
quotaLevel VARCHAR(32) NOT NULL,
quota1 INT NOT NULL,
quota2 INT NOT NULL,
PRIMARY KEY (level)
);
Every user will have an entry in the users table, but not necessarily in the user_info table. Each user in the user_info table has a quotaLevel corresponding to the quotaLevel column in the quota_levels table. Possible values for quotaLevel are BRONZE, SILVER, GOLD, and PLATINUM.
I could go into a long explanation of why it is set up this way, but it would be quicker to just say that this structure cannot be changed.
If the user exists, I want to get the quota1 value of their quotaLevel. If the user doesn't exist, the quota1 value for BRONZE should be returned.
I want to do this with ONE query. Can it be done and how?
SELECT u.Name,
COALESCE(ql.quota1, (SELECT quota1 FROM quota_level WHERE quotaLevel = 'BRONZE'))
FROM users u
LEFT JOIN user_info ui
INNER JOIN quota_level ql
ON ui.quotaLevel = ql.quotaLevel
ON u.id = ui.userID

selecting a user of every type

I have a query against two databases that I'm trying to execute. The first table is just user information and is referenced by a privilege table. For my query I'm trying to find a set of super users, they are users that have every current privilege in the privilege table. It is set up as follows:
create table MEMBER
( id int not null,
name varchar(10),
bdate date,
sex char,
pc_id int not null,
PRIMARY KEY (mid),
FOREIGN KEY (pc_id) REFERENCES PLEDGECLASS(id))
create table MEMBER_PRIVILEGE
( mid int not null,
pid int not null,
PRIMARY KEY (mid,pid),
FOREIGN KEY (mid) REFERENCES MEMBER(id),
FOREIGN KEY (pid) REFERENCES PRIVILEGE(id))
create table PRIVILEGE
( id int,
pname varchar(15)
PRIMARY KEY(id))
Although obviously the incorrect query, I'm trying to do something equivalent to the following:
Select name
From MEMBER,MEMBER_PRIVILEGE
Where id=mid AND pid = ALL (select id
From PRIVILEGE);
SELECT *
FROM MEMBER
WHERE NOT EXISTS (
SELECT *
FROM MEMBER_PRIVILEGE LEFT JOIN PRIVILEGE ON MEMBER_PRIVILEGE.pid = PRIVILEGE.id)
WHERE MEMBER_PRIVILEGE.mid = MEMBER.id AND PRIVILEGE.id IS NULL
)
Try this ::
Select name, (select count(id) from PRIVILIGE) as p_count
From MEMBER m
inner join MEMBER_PRIVILEGE mp on (m.id=mp.mid)
group by mp.mid having count(*) = p_count;