Issues with SQL JOIN failing - php

I have the following JOIN I am attempting to create.
SELECT rating_draft_result.COUNT(id), rating_draft_result.user_id, rating_draft_result.result
FROM rating_draft_result
INNER JOIN users ON
rating_draft_result.user_id, rating_draft_result.result = users.id
I am trying to COUNT the total id's of the rating_draft_result table and then also SELECT the user_id and result from that table. Then I am trying to match the user_id and result from the rating_draft_result table to the user's id column. Then I want to get the username from the user's table where the id matches, but I can't figure that part out and I am getting an error anyways with the following code.
I get the following error..
Survey SELECT total count prepare() failed: You have an error in your
SQL syntax; check the manual that corresponds to your MySQL server
version for the right syntax to use near '.id' at line 4
My database tables look like this...
users
CREATE TABLE `users` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`firstname` varchar(100) COLLATE utf8_unicode_ci NOT NULL,
`lastname` varchar(100) COLLATE utf8_unicode_ci NOT NULL,
`email` varchar(100) COLLATE utf8_unicode_ci NOT NULL,
`phone_number` varchar(15) COLLATE utf8_unicode_ci NOT NULL,
`username` varchar(100) COLLATE utf8_unicode_ci NOT NULL,
`password` varchar(100) COLLATE utf8_unicode_ci NOT NULL,
`salt` varchar(32) COLLATE utf8_unicode_ci NOT NULL,
`joined` datetime NOT NULL,
`group` int(11) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=105 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci
rating_draft_result
CREATE TABLE `rating_draft_result` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` int(11) NOT NULL,
`result` int(11) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=28 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci
What am I doing wrong in my query?
DESIRED OUTPUT:
users
CREATE TABLE users (
id``firstname``lastname``email``phone_number``username``password``salt``joined group
1 Jack Johnson jack#email.com 2222 jackusername ffd fdddfd today 1
10 Tom Thompson fdfdfddf#fef.com 5555 Tomusername
rating_draft_result
`id` `user_id` `result`
20 1 10
I want to be able to match the rating_draft_result's user_id and result with the user table's id field.
So I want to get the jackusername and tomusername fields.

Check JOIN condition
SELECT rating_draft_result.user_id, rating_draft_result.result, COUNT(*)
FROM rating_draft_result
INNER JOIN users
ON rating_draft_result.user_id = users.id
GROUP BY rating_draft_result.user_id, rating_draft_result.result;
You have
ON rating_draft_result.user_id, rating_draft_result.result = users.id

The problem is in your JOIN ON clause. You need to change it like
INNER JOIN users ON
rating_draft_result.user_id = users.id
(OR) If you want to have both the conditions then use a AND operator like
FROM rating_draft_result
INNER JOIN users ON
rating_draft_result.user_id = users.id
AND rating_draft_result.result = users.id
Change your entire query to be like below
SELECT COUNT(rating_draft_result.id),
rating_draft_result.user_id,
rating_draft_result.result
FROM rating_draft_result
INNER JOIN users ON
rating_draft_result.user_id = users.id
AND rating_draft_result.result = users.id;

Related

mySql combine two SELECT queries with JOIN

I have two mySql queries to get result from databases. I am trying to join them together.
Query 1:
SELECT userEwallets.id as ewalletId, users.id as userId , money_repositories.money as money, a.nestedUserId
FROM userEwallets
JOIN users ON users.id = userEwallets.userId
JOIN money_repositories ON userEwallets.id = money_repositories.ewalletId
WHERE ewalletNumber = 'SHIRR937303656'
Query 2:
SELECT nested.id as nestedUserId
FROM userEwallets as nested
JOIN users ON users.id = nested.userId
JOIN money_repositories ON nested.id = money_repositories.ewalletId
WHERE ewalletNumber = 'SHIRR9122331743'
and then my combination command:
SELECT userEwallets.id as ewalletId, users.id as userId , money_repositories.money as money, a.nestedUserId
FROM (
SELECT nested.id as nestedUserId
FROM userEwallets as nested
JOIN users ON users.id = nested.userId
JOIN money_repositories ON nested.id = money_repositories.ewalletId
WHERE ewalletNumber = 'SHIRR912233'
) as a
JOIN users ON users.id = userEwallets.userId
JOIN money_repositories ON userEwallets.id = money_repositories.ewalletId
WHERE ewalletNumber = 'SHIRR93730'
I get this error:
#1054 - Unknown column 'userEwallets.id' in 'field list'
Both of commands are same but they have simple difference as ewalletNumber in where clause
UPDATE WITH DATABASE STRUCTURE
money_repositories table:
CREATE TABLE IF NOT EXISTS `money_repositories` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`userId` int(11) NOT NULL,
`ewalletId` int(11) NOT NULL,
`money` int(11) NOT NULL,
`createdAt` int(11) NOT NULL,
`updatedAt` int(11) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_persian_ci AUTO_INCREMENT=4 ;
userEwallets table:
CREATE TABLE IF NOT EXISTS `userEwallets` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`userId` int(11) NOT NULL,
`ewalletNumber` varchar(15) COLLATE utf8_persian_ci NOT NULL,
`currencySymbol` varchar(5) COLLATE utf8_persian_ci NOT NULL,
`createdAt` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`updatedAt` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_persian_ci AUTO_INCREMENT=7 ;
users table:
CREATE TABLE IF NOT EXISTS `users` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(20) COLLATE utf8_persian_ci NOT NULL,
`password` varchar(65) COLLATE utf8_persian_ci NOT NULL,
`name` varchar(20) COLLATE utf8_persian_ci NOT NULL,
`family` varchar(20) COLLATE utf8_persian_ci NOT NULL,
`birthDay` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00' ON UPDATE CURRENT_TIMESTAMP,
`email` varchar(20) COLLATE utf8_persian_ci NOT NULL,
`mobileNumber` varchar(15) COLLATE utf8_persian_ci NOT NULL,
`verifyCode` varchar(5) COLLATE utf8_persian_ci NOT NULL,
`photoUri` varchar(50) COLLATE utf8_persian_ci NOT NULL,
`ebanNumber` varchar(20) COLLATE utf8_persian_ci NOT NULL,
`status` tinyint(1) NOT NULL,
`createdAt` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
`updatedAt` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_persian_ci AUTO_INCREMENT=35 ;
userEwallets.id should be a.id in Select of your combination command. Because you are getting subquery as a.
Modified combined query;
SELECT a.id AS ewalletId,
users.id AS userId,
money_repositories.money AS money,
a.nesteduserid
FROM (SELECT nested.id AS nestedUserId,
nested.id,
nested.ewalletnumber
FROM userewallets AS nested
JOIN users
ON users.id = nested.userid
JOIN money_repositories
ON nested.id = money_repositories.ewalletid
WHERE nested.ewalletnumber = 'SHIRR912233') AS a
JOIN users
ON users.id = userewallets.userid
JOIN money_repositories
ON userewallets.id = money_repositories.ewalletid
WHERE a.ewalletnumber = 'SHIRR93730'
camleCase query fixed:
SELECT a.id AS ewalletId,
users.id AS userId,
money_repositories.money AS money,
a.nestedUserId
FROM (SELECT nested.id AS nestedUserId,
nested.id,
nested.ewalletNumber
FROM userEwallets AS nested
JOIN users ON users.id = nested.userId
JOIN money_repositories ON nested.id = money_repositories.ewalletId
WHERE nested.ewalletNumber = 'SHIRR912233') AS a
JOIN users ON users.id = nested.userId
JOIN money_repositories ON userEwallets.id = money_repositories.ewalletId
WHERE a.ewalletNumber = 'SHIRR937303'
Because you are not including table userEwallets in the query except in the sub query which won't be recognized outside the subquery. Try
UPDATE
Select
users.id as userId, userEwallets.id As ewalletId,money_repositories.money
From
users
Inner Join
userEwallets ON userEwallets.userId= users.id
Inner Join
money_repositories ON money_repositories.userId=users.id
And
money_repositories.ewalletId = userEwallets.id
Where
userEwallets.ewalletNumber = 'SHIRR93730'

Multiple LEFT JOIN doesn't work on SUM()

So the idea is to get information from 3 tables:
R_Regle: rule table, basic info of the rule
C_Commentaire: the number of comments this rule has
I_Interet: The SUM of all upvotes and downvotes from one rule.
The structure of my I_Interet:
I_ID / I_Idregle / I_Idpseudo / I_Upvote / I_Downvote
Each row can only contain 1 upvote or 1 downvote.
so with this request:
SELECT R_Id, R_Date, R_Titre, R_Contenu, R_Etape, COUNT(C_Commentaire.C_IdRegle) AS CountComment, SUM(I_Interet.I_Up) AS Up ,SUM(I_Interet.I_Down) AS Down
FROM R_Regle
LEFT JOIN C_Commentaire ON C_Commentaire.C_IdRegle = R_Regle.R_Id
LEFT JOIN I_Interet ON I_Interet.I_IdRegle = R_Regle.R_Id
GROUP BY R_ID
I try to obtain all those information.
Problem is:
COUNT(C_Commentaire.C_IdRegle) AS CountComment
Gives me the count of all COMMENTS and UPVOTES/DOWNVOTES.
So if there are 4 comments and 3 downvotes, it will count it like that
$row['CountComment'] = 7;
But obviously, I don't want that. I want
$row['CountComment'] = 4;
Any ideas?
EDIT 1:
Here are the tables:
R_REGLE
CREATE TABLE `R_Regle` (
`R_Id` int(11) NOT NULL AUTO_INCREMENT,
`R_Auteur` varchar(32) COLLATE utf8_unicode_ci NOT NULL,
`R_Date` date NOT NULL,
`R_Titre` varchar(150) CHARACTER SET latin1 NOT NULL,
`R_Contenu` text CHARACTER SET latin1 NOT NULL,
`R_Etape` int(11) NOT NULL DEFAULT '1' COMMENT '1 = discussion 2= VOTE',
PRIMARY KEY (`R_Id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
C_COMMENTAIRE
CREATE TABLE `C_Commentaire` (
`C_Id` int(11) NOT NULL AUTO_INCREMENT,
`C_Date` datetime NOT NULL,
`C_Pseudo` varchar(32) COLLATE utf8_unicode_ci NOT NULL,
`C_Contenu` text COLLATE utf8_unicode_ci NOT NULL,
`C_IdRegle` int(11) NOT NULL,
PRIMARY KEY (`C_Id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
I_INTERET
CREATE TABLE `I_Interet` (
`I_Id` int(11) NOT NULL AUTO_INCREMENT,
`I_IdRegle` int(11) NOT NULL,
`I_Pseudo` varchar(30) COLLATE utf8_unicode_ci NOT NULL,
`I_Up` tinyint(1) NOT NULL DEFAULT '0',
`I_Down` tinyint(1) DEFAULT '0',
PRIMARY KEY (`I_Id`)
) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
I can suggest using correlated query.. not sure if thats what you want since you didn't post any table structures its hard to know :
SELECT R_Id, R_Date, R_Titre, R_Contenu, R_Etape,
(select COUNT(*) from C_Commentaire where C_Commentaire.C_IdRegle = R_Regle.R_Id) AS CountComment,
SUM(I_Interet.I_Up) AS Up ,
SUM(I_Interet.I_Down) AS Down
FROM R_Regle
LEFT JOIN I_Interet ON I_Interet.I_IdRegle = R_Regle.R_Id
GROUP BY R_ID
Write your query as below:
SELECT R_Regle.R_Id, R_Regle.R_Date, R_Regle.R_Titre, R_Regle.R_Contenu, R_Regle.R_Etape,
COUNT(C_Commentaire.C_IdRegle) AS CommentCounts,
SUM(I_Interet.I_Up) AS Up,
SUM(I_Interet.I_Down) AS Down
FROM R_Regle
LEFT JOIN C_Commentaire ON R_Regle.R_Id = C_Commentaire.C_IdRegle
LEFT JOIN I_Interet ON R_Regle.R_Id = I_Interet.I_IdRegle
GROUP BY R_Regle.R_ID
In your query there are duplicate records arisen when you make a left join among the three tables.
The following query is one of few ways to achieve your desired result.
SELECT
t.*,
SUM(I_Interet.I_Up) AS Up,
SUM(I_Interet.I_Down) AS Down
FROM
(
SELECT
R_Id,
R_Date,
R_Titre,
R_Contenu,
R_Etape,
COUNT(c_commentaire.C_IdRegle) countComment
FROM
R_Regle LEFT JOIN C_Commentaire ON C_Commentaire.C_IdRegle = R_Regle.R_Id
GROUP BY R_Regle.R_Id ) t
LEFT JOIN I_Interet ON I_Interet.I_IdRegle = t.R_Id
GROUP BY t.R_Id

Issues getting bind_results to work in while loop

I am attempting to loop through my bind_results, but it is not working like I need it to. I have tried this 20 different ways and the result is always the same. I get only the first records of $survey_user_id and $survey_result to echo out.
Also when I do a COUNT like I did in my query, do I need to loop through that as well? Because as of now it is only counting 1 record when there is multiple id's for rating_draft_result.id .
try {
$survey_title_stmt = $con->prepare("SELECT COUNT(rating_draft_result.id), rating_draft_result.user_id, rating_draft_result.result
FROM rating_draft_result
INNER JOIN users ON
rating_draft_result.user_id = users.id
AND rating_draft_result.result = users.id");
if ( !$survey_title_stmt || $con->error ) {
// Check Errors for prepare
die('Survey SELECT total count prepare() failed: ' . htmlspecialchars($con->error));
}
if(!$survey_title_stmt->execute()) {
die('Survey SELECT total count execute() failed: ' . htmlspecialchars($survey_title_stmt->error));
}
$survey_title_stmt->store_result();
} catch (Exception $e ) {
die("Survey SELECT total count: " . $e->getMessage());
}
$survey_title_stmt->bind_result($survey_id, $survey_user_id, $survey_result);
while ($survey_title_stmt->fetch()) {
$survey_id;
$survey_user_id;
$survey_result;
}
?>
<div class="survey_results_out">
<div id="survey_results_title">Survey Results</div>
<div class="survey_popup_container">
<a class="survey_popup" href="javascript:void(0)">Who drafted best results</a>
<div id="">Users that completed this survey</div><?php echo $survey_id; ?>
<div class="survey_popup_wrap light_admin">
<a class="close_survey_popup" href="javascript:void(0)">X</a>
<div id="indexpopupTitleWrap">
<div id="indexpopupTitle">Results of who drafted the best</div>
</div>
<div id="survey_results_content_wrap">
<div id="survey_results_content_usernames">
<?php
echo $survey_user_id;
echo $survey_result;
?>
My database tables look like this...
users
CREATE TABLE `users` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`firstname` varchar(100) COLLATE utf8_unicode_ci NOT NULL,
`lastname` varchar(100) COLLATE utf8_unicode_ci NOT NULL,
`email` varchar(100) COLLATE utf8_unicode_ci NOT NULL,
`phone_number` varchar(15) COLLATE utf8_unicode_ci NOT NULL,
`username` varchar(100) COLLATE utf8_unicode_ci NOT NULL,
`password` varchar(100) COLLATE utf8_unicode_ci NOT NULL,
`salt` varchar(32) COLLATE utf8_unicode_ci NOT NULL,
`joined` datetime NOT NULL,
`group` int(11) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=105 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci
rating_draft_result
CREATE TABLE `rating_draft_result` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` int(11) NOT NULL,
`result` int(11) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=28 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci
DESIRED OUTPUT:
users id``firstname``lastname``email``phone_number``username``password``salt``joined group
1 Jack Johnson jack#email.com 2222 jackusername ffd fdddfd today 1
10 Tom Thompson fdfdfddf#fef.com 5555 Tomusername
rating_draft_result
`id` `user_id` `result`
20 1 10
I want to be able to match the rating_draft_result's user_id and result with the user table's id field.
So I want to get the jackusername and tomusername fields.
Not quite sure what it is you want for that data.
However the following might help:-
This gets the rating_draft_result.id and the 2 user names that go with it
SELECT rating_draft_result.id, u1.username, u2.username
FROM rating_draft_result
INNER JOIN users u1 ON rating_draft_result.user_id = u1.id
INNER JOIN users u2 ON rating_draft_result.result = u2.id
This gets the count of rating_draft_result.id for each pair set of usernames in the rating_draft_result table
SELECT COUNT(rating_draft_result.id), u1.username, u2.username
FROM rating_draft_result
INNER JOIN users u1 ON rating_draft_result.user_id = u1.id
INNER JOIN users u2 ON rating_draft_result.result = u2.id
GROUP BY u1.username, u2.username

Cannot retrieve column information from database

I have two tables, namely user_info and comments. I want to join the tables, so i can relate the user_id from the from comments after the inner join has happened, which will join based on the id columns. The whole reason for this is so i can find out what the id is of a user who posts a comment on a users profile, which i store in user_id.
SHOW CREATE TABLE user_info
CREATE TABLE `user_info` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(12) COLLATE utf8_unicode_ci NOT NULL,
`pass` varchar(40) COLLATE utf8_unicode_ci DEFAULT NULL,
`joined` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
UNIQUE KEY `username` (`username`))
ENGINE=InnoDB AUTO_INCREMENT=64 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci'
SHOW CREATE TABLE comments
'CREATE TABLE `comments` (
`id` int(11) DEFAULT NULL,
`comment` text COLLATE utf8_unicode_ci,
`date_posted` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`user_id` int(11) DEFAULT NULL)
ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci'
The query code
try {
$result = $db->prepare("SELECT user_id
FROM comments
INNER JOIN user_info USING (id)
WHERE id = :user");
$result->bindParam(':user', $post_session_user_id);
$result->execute();
$comment_details = $result->fetch();
}
How comment_details is stored
$comment_id = $comment_details[0];
and then i do a var_dump that returns NULL
var_dump($comment_id);
Any ideas what is wrong?
I think you should not be using USING as that works only when you have 2 fields, one in each table both having the same name.
In your tables comment.user_id holds the user_info.id
So your query should probably be
SELECT user_id
FROM comments
INNER JOIN user_info ON user_info.id = comments.user_id
WHERE comments.id = :user

"my network" function with sql subquery

I need a little help for one sql query;
here is my basic user database table
CREATE TABLE IF NOT EXISTS `users` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`email` varchar(100) NOT NULL,
`pass` varchar(255) NOT NULL,
`fname` varchar(50) NOT NULL,
`lname` varchar(40) NOT NULL,
`network` varchar(10) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=27 ;
and here is my basic topics database table
CREATE TABLE IF NOT EXISTS `topics` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`userid` varchar(100) NOT NULL,
`title` varchar(255) NOT NULL,
`body` text,
`tags` varchar(256) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=2 ;
What I'm trying to do is;
i.e. list all topics from users who joined "harvard" network
You just need a simple JOIN. Join the tables on the userID (of those who are in "harvard").
SELECT title,body
FROM topics, users
WHERE userid = users.id
AND network = 'harvard'
Or using the JOIN keyword:
SELECT title,body
FROM topics
JOIN users ON userid = users.id
WHERE network = 'harvard'
This should do the trick, I think:
SELECT
title
FROM
topics t
INNER JOIN
users u ON t.userid=u.id
WHERE
network='Harvard'
SELECT t.title
FROM users u
INNER JOIN topics t ON u.id = t.userid
WHERE u.network = 'harvard'
GROUP BY u.id

Categories