I am performing MySQL functions using PHP for my webpages.
I have got a table
table name -> users
uname oname
john alex
john murray
john joseph
john ray
and another table
table name -> more_info
fname lname more
alex some name some info
murray // //
joseph // //
ray // //
What I am trying to do is to run a query
Retrieve all the oname column values which are matched with uname john
This statement successfully retrieves the oname column values if uname = john
SELECT oname FROM users WHERE uname = 'john '
Now I want a statement something like this, based on the previously retrieved oname column values
SELECT * FROM more_info WHERE fname=oname // previos ones
I guess its Join orinnerJoin but somehow I am unable to get the correct syntax of it or any other simple query to do this.
My approach
I thought to retrieve the oname column values first and then inside a for loop, based on number of rows returned run a query for each column, but this approach eats up my server.
Try this query,
SELECT * FROM `more_info` `i` INNER JOIN `users` `u` ON `i`.`fname`=`u`.`oname` WHERE `u`.`uname`="john"
I think the following query wll help u.
SELECT * FROM `more_info` WHERE `fname` = (SELECT `oname` FROM `users` WHERE `uname` = "john")
You can merge your two queries into one by a simple INNER JOIN
SELECT * FROM more_info mi
INNER JOIN users u ON mi.fname = u.oname
WHERE u.uname = 'john'
If there is some chance of null values in more_info table, then you should use LEFT JOIN instead of INNER JOIN. Otherwise it is not necessary.
SELECT * FROM users A
INNER JOIN more_info B
ON A.oname = B.fname
WHERE uname = 'john'
See the MySQL documentation on the JOIN syntax for details.
Related
I am trying to only show unique userIds (userIds are (0,1,2,3,4,5,6,7,8,9 etc...) for the query I am running. I tried using DISTINCT in my query, but it only shows me unique values of the rows that have 2 or more of the same userId.
Is there a way I can use php to only show the unique values. My weak points are arrays and it makes it more complicated because its using data from a MySQLi query.
Example right now I have with the query now (lets say its GROUP BY rentPaid DESC and the rent total is 800.00 for all users):
userID rentPaid rentMonth
2--------800.00------April
1--------500.00------April
3--------400.00------April
3--------400.00------April
1--------200.00------April
1--------100.00------April
Example desired output:
userID rentPaid rentMonth
2--------800.00------April
1--------500.00------April
3--------400.00------April
Can I do this with MYSQL because I tried DISTINCT and it wouldn't work, how about PHP?
Query:
SELECT
properties.*,
leases.*,
users.userId, users.primaryPhone,
CONCAT(users.userFirstName,' ',users.userLastName) AS user,
admins.adminName, payments.*
FROM
properties
LEFT JOIN leases ON properties.propertyId = leases.propertyId
LEFT JOIN assigned ON properties.propertyId = assigned.propertyId
LEFT JOIN admins ON assigned.adminId = admins.adminId
LEFT JOIN users ON properties.propertyId = users.propertyId
LEFT JOIN payments ON properties.propertyId = payments.propertyId
WHERE
payments.rentMonth = '$currentMonth' AND
payments.rentYear = '$currentYear'
Edit: Please excuse my formatting, this is my first post.
Edit: Added query....its long, but works lol. I only want unique userIds (no double or triple userIds etc...)
I suspect this is what you want:
SELECT userID, MAX(rentPaid) AS maxRentPaid, rentMonth
FROM yourTable
WHERE rentMonth = "April"
GROUP BY userID
ORDER BY maxRentPaid
I have two tables first and second.
first Table:
ID NAME ADDRESS
1 test testing address
2 test1 testing address
3 test2 testing address
4 test3 testing address
second Table:
T_ID Partner_id date
1 2 12345678
3 4 32164584
If input T_id is given. Then corresponding Partner_id is taken and it is compared with the ID from first table and corresponding row should be selected.
Can you please tell me.
In php I can write this with two queries but I want it to be in a single query.
Queries in php:
$q=mysqli_query($conn, "SELECT Partner_id from second where T_ID=1");
$qa=mysqli_fetch_array($q);
$w=mysqli_query($conn, "SELECT * from first where ID=$qa[0]");
But, how to combine this two statements?
The specified result can be returned using a query with a join operation.
SELECT f.*
FROM first f
JOIN second s
ON s.Partner_id = f.ID
WHERE s.T_ID=1
Note that there is a potential for this to return more rows that the original, if the first query returns more than one row. (That is, we don't assume that T_ID is unique in second, or that every row with a given T_ID value will have identical values for Partner_id.)
There are other query patterns that will return an equivalent result, but the join operation is the normative pattern.
try to use union ,see this this link
where The SQL UNION operator combines the result of two or more SELECT statements.
SELECT * FROM first WHERE ID IN( SELECT Parent_id FROM second WHERE T_ID = 1 )
or
SELECT * FROM first WHERE ID = ( SELECT Parent_id FROM second WHERE T_ID = 1 )
SELECT * FORM first_table AS f
JOIN second_table AS s
ON s.parent_id =f.id
WHERE s.T_ID = $id
I've been Googling for most of my day now but I can't seem to find the right answer. Maybe because I don't really know in which direction to look (join? exist?). What I have is 3 tables:
There is a table named 'groups' and 'languages' containing the actual group- and language data but that's not important right now.
The user should be able to generate a list with all members, depending on the selected groups and/or languages. The groups/languages that the user selected are saved in two separate array's containing the IDs ($aGroups and $aLangs).
What I want/need is to SELECT * FROM members WHERE ...
And that's where I got stuck. I've tried joins, I've tried IN(), I've tried EXIST but nothing seems to work right.
Any help is greatly appreciated!
If you want to select members by languages and groups, you can do something like this :
$query = "select * from members as m
left join group_members as gm on gm.member_id = m.id
left join language_members as lm on lm.member_id = m.id";
if(isset($aGroups)) {
$query .= " where group_id in (".implode(",", $aGroups).")";
if(isset($aLangs)) {
$query .= " and language_id in (".implode(",", $aLangs).")";
}
}
elseif(isset($aLangs)) {
$query .= " where language_id in (".implode(",", $aLangs).")";
}
I think you just need some brackets:
//assuming you have ids stored in $lang and $group
SELECT * FROM members WHERE (SELECT group_id FROM group_members WHERE member_id=members.id)='$group'
AND (SELECT lang_id FROM language_members WHERE member_id=members.id)='$lang'
The trick is "members.id", DB will call subquery for every member to find out if the condition for group and lang is met.
Select m.* FROM members m, group_members gm, language_members lm
WHERE
lm.member_id=m.id AND
m.id=gm.member_id AND
<<<< START YOUR OWN WHERE HERE.
There might be an easy solution here, but it seems to have me tripped up. I'm trying to query a table based on an array of values in two columns. Here is the pertinent table structure and sample data
comment table
id, userId, articleId .... etc etc
article table
id, userId .... etc etc
Data: UserIds = 3, 10. ArticleIds = 1, 2
Let's say I'm trying to find all the comments for a particular set of article IDs: 1,2
I can easily use this query
select * from comments WHERE articleId IN(1,2)
However, here is where it gets complex. I have a query that executes prior to the comments query that determines the appropriate article IDs. Those IDs are in an array. Also in an array are the corresponding user IDs for each article.
What I want to do now is query the comments table for only the articles in the array (1,2) AND only for those comments made by the original author (3, 10).
The simple query above will bring back all the comments for articleId 1 and 20. So for example I can't figure out where to add another conditional that says onyl comments for articleId 1, 20 AND corresponding userId, 3, 10.
Any help or suggestions would be much appreciated!
I think the simplest way is to write:
SELECT comments.*
FROM articles
JOIN comments
ON articles.id = comments.articleId
AND articles.userId = comments.userId
WHERE articles.id IN (1, 2)
;
The AND articles.userId = comments.userId clause is what enforces your "only for those comments made by the original author" requirement.
Alternatively, you can use an EXISTS clause:
SELECT *
FROM comments
WHERE articleId IN (1, 2)
AND EXISTS
( SELECT 1
FROM articles
WHERE id = comments.articleId
AND userId = comments.userId
)
;
or a single-row subquery:
SELECT *
FROM comments
WHERE articleId IN (1, 2)
AND userId =
( SELECT userId
FROM articles
WHERE id = comments.articleId
)
;
Have you tried just
select * from comments WHERE articleId IN(1,2) and authorId in (3,10)
If not, please update your question why it's so.
You can add as many IN statements as you want:
select * from comments WHERE articleId IN(1,2) AND userId IN (3,10)
Can't you just make the query that runs first a subquery within your stated query:
SELECT * FROM `comments` WHERE `articleId` IN(1,2) AND `userId` IN (__subquery__)
-- you can use subquery
select * from comments WHERE articleId IN(1,2)
and userId in ( select userId from article where id in (1,2) )
Hi I have a table like this
ID UserName
1 test#test.com
2 test#test.com
3 john#stack.com
4 test#test.com
5 adam#stack.com
6 john#stack.com
I need an output like this. I need only repeated rows list. How can I create this kind of an output using mysql query.
ID UserName Count
1 test#test.com 3
2 john#stack.com 2
Please help me.
Thanks.
I had the same problem some time ago and solved it like this (as far as I remember):
SELECT *
FROM tableA INNER JOIN
(SELECT DISTINCT MAX(id) as id, type_id, temp FROM tableA GROUP BY type_id, temp) AS t
ON tableA.id = t.id
AND tableA.type_id = t.type_id
AND tableA.temp = t.temp
You join the table with itself selecting the ids that are duplicate. The fields that should be tested against duplicate values are in this case type_id and temp. If you need more or less fields that should be considered as duplicates you can adjust the fields.
I don't know if this helps in your case and if it can be done in a more simple way, so I'm prepared for downvotes ;-)
Edit: removed last condition AND tableA.id < t.id as suggested by ypercube because it leads to 0 results.
It looks like you're trying to pull the following data:
First ID for a given UserName
The UserName itself
The total number of IDs for that UserName
This query should do the trick:
SELECT
MIN(id),
UserName,
COUNT(id)
FROM users
GROUP BY UserName;
since the ID is not unique so its a bit not logical to get the sum of unique UserName from the table.
If the ID is not required we can get the result from single query.
SELECT UserName, COUNT(UserName) AS Count
FROM TableName GROUP BY UserName
HAVING COUNT(UserName) > 1;
But in the case of ID in the result it will be a more complicated query including sub-query and inner table.
SELECT UserName
, COUNT(*) AS `Count`
FROM tableX
GROUP BY UserName
HAVING COUNT(*) > 1
Hi this is the right answer.
SELECT UserName, COUNT(UserName) AS Count
FROM TableName GROUP BY UserName
HAVING COUNT(UserName) > 1;