i have two tables in my db .. one is Messages and the other is Contacts... both tables contain the mobile_number field.. in Contacts table there is no duplicate numbers ... but in Messages tables there are several duplicate numbers in mobileNo field...what i am doing is write now i am selecting the distinct mobile numbers from the Messages tables and then i am comparring the distinct numbers from the contacts table ... so if the messages_mobileNo is found on the contacts table then give me the contact name against the number otherwise messages_mobileNo ... so the problem is distinct not working .. i am not able to get the distinct numbers from the Messages table ... it is showing me the duplicate numbers
here is my query
SELECT DISTINCT Message.mobileNo,
Contact.mobileNo,
Contact.workNo,
Contact.homeNo,
Contact.other,
Contact.name,
Message.body,
Message.idTextMessage
FROM cakephp_db.textmessage AS Message
LEFT JOIN cakephp_db.contacts AS Contact ON (Message.user_id = Contact.user_id
AND ((Message.mobileNo = Contact.mobileNo)
OR (Message.mobileNo = Contact.workNo)
OR (Message.mobileNo = Contact.homeNo)
OR (Message.mobileNo = Contact.other)))
WHERE Message.User_id = 23
ORDER BY Message.idTextMessage DESC LIMIT 6
So your trying to get the last 6 messages of a person if I'm right?
SELECT Message.mobileNo,
Contact.mobileNo,
Contact.workNo,
Contact.homeNo,
Contact.other,
Contact.name,
Message.body,
Message.idTextMessage
FROM cakephp_db.textmessage AS Message
LEFT JOIN cakephp_db.contacts AS Contact ON Message.user_id = Contact.user_id
AND Message.mobileNo IN (Contact.mobileNo, Contact.workNo, Contact.homeNo, Contact.other)
WHERE Message.User_id = 23
GROUP BY Message.mobileNo
ORDER BY Message.idTextMessage DESC LIMIT 6
add a GROUP BY Message.mobileNo before your ORDER BY
If you are using MySQL SELECT DISTINCT with an ORDER BY added to it, you will have to create a temporary table where it can store its results. Here is a link offering more help:
MySQL DISTINCT Optimization
Related
I have a database of comics with a table of comics, credits, and contributor details. I am trying to filter my table using this SQL query:
The select parameters have * to show all but don't seem to show here
SELECT
cc.*,
ct.*,
cpub.*,
c.*,
cs.*
FROM
comic_types AS ct,
comics_publisher AS cpub,
comics AS c,
comics_series AS cs,
comic_credits AS cc
WHERE
c.comic_indexkey = cc.comic_index_key
AND cpub.publisher_index_key = c.comic_publisher
AND c.comic_series = cs.comics_seriesindexkey
AND ct.comic_typeindexkey = c.comic_type
AND cpub.publisher_index_key = c.comic_publisher
ORDER BY
comic_title ASC,
comic_series ASC
LIMIT 0, 15
The Limit values are placed there for pagination.
Some comics have the same contributor with a different role (e.g. comic A has person B as author and illustrator). This means I have two results that are the same comic. I have used an array and continue statement to make the duplicate record not show.
$comics_in_table = array();
if (in_array($comic['comic_indexkey'], $comics_in_table)) {
continue;
}
The problem this has created is the pagination only shows 5 per page rather than 15, presumably because it detects that 10 of the results have been 'hidden'
Following the kind help so far, created this:
SELECT
cc.*,
ct.*,
cpub.*,
c.*,
cs.*
FROM
comic_types AS ct,
comics_publisher AS cpub,
comics AS c,
comics_series AS cs,
comic_credits AS cc
WHERE
c.comic_indexkey = cc.comic_index_key
AND cpub.publisher_index_key = c.comic_publisher
AND c.comic_series = cs.comics_seriesindexkey
AND ct.comic_typeindexkey = c.comic_type
AND cpub.publisher_index_key = c.comic_publisher
GROUP BY
cc.comic_index_key
ORDER BY
c.comic_title ASC,
c.comic_series ASC
LIMIT 0, 15
And SQL returns this issue:
#1055 - Expression #1 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'sewters.cc.credit_index_key' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by
Try either to use
SELECT DISTINCT cc.*, ct.* ...
or append a
GROUP BY fieldname
at the end of your SELECT query, where fieldname is the database column that you want grouped into one entry.
I have two tables, one for registered users and one to store votes.
We are logging in with registrants.id and registrants.zipcode. Once they vote their votes are inserted into the votes table, along with their Registration ID.
Im trying to right a select statement that returns a record that will select all the records for Matched ID and Zipcode, but the ID is not in the Votes.voter column. i have tried all kinds of variations of all the joins i can think of. is it something simple i am missing.
SELECT * FROM registrants
LEFT JOIN votes on registrants.id = votes.voter
WHERE registrants.id = 1 AND registrants.zipcode = 46706 and votes.voter <> 1
Perhaps a not exists query:
select * from registrants
where registrants.zipcode = '46706'
and not exists (select 1 from votes where registrants.id = votes.voter)
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 here.
log (stands for logbook)
act (stands for actions)
log
contains columns: logid, userid, actid
act
contains columns: actid, amount
Amount stands for an amount of points (e.g. 50 of 700 or 5) the user (userid) receives when the corresponding actid is inserted in the logbook (log).
What I'm trying to achieve is that when you search for userid 1, that all rows from log where userid = 1 are selected. Then, from these selected log-rows, the actids should be looked up in the table act, and the amounts should be summed.
In short:
select log-rows where userid = 1
take all the actids from these rows
find the matching amount in the act table
sum all these amounts
I started with this query:
SELECT log.logid, log.userid, log.actid, act.actid, act.amount
FROM log
JOIN act
ON act.actid = log.actid
WHERE log.userid = '1'
This got me a table with (among other things)
userid | amount
---1----|--20---
---1----|--40---
---1----|---5---
---1----|--10---
Now I would like to sum all these amounts and echo the total, but unfortunately I can't find a working query for this.
EDIT:
I used the query that Naruto provided me to sum these amounts. This works like a charm now! The query:
SELECT log.userid, sum(act.amount) FROM log JOIN act ON act.actid = log.actid WHERE log.userid = '1'
The next thing that I'm trying is to get not only the summed amount from the user with userid = 1, but also from the other users in the user-table. After that, I'd like to use these summed amounts in the following query:
$result = $mysqli->query("SELECT * FROM `db`.`user` ORDER BY `summed_amount` DESC");
In which summed_amount is the summed amount generated by Naruto's query.
MySQL has an Aggregate function called sum() which can sum all the records.
So your query will be
SELECT log.userid, sum(act.amount) FROM log JOIN act ON act.actid = log.actid WHERE log.userid = '1'
http://dev.mysql.com/doc/refman/5.7/en/group-by-functions.html#function_sum
To get sum of all users by a single query use group by clause.Here it will calculate sum of amaount for each user and return the result.
SELECT log.userid, sum(act.amount) FROM log JOIN act ON act.actid = log.actid group by log.userid
Edit:- To get order by desc
SELECT log.userid, sum(act.amount) FROM log JOIN act ON act.actid = log.actid group by log.userid order by sum(act.amount) desc
Hi I am new for developing.Kindly bear my codings. I have created a table arlog with id(auto increment), status, ticket number and code. Ticket and code number is set as unique. That is the duplicate of this combination cannot inserted again. But individually ticket number or cpt can be inserted as many times.It works fine. Now I want to use select query with another table with respect to the arlog table ticket number and code.Here is the select statement
$result = mysql_query("SELECT * FROM `ar` C WHERE provider='".$_SESSION['PROVIDER']
."' AND C.`TicketNo` IN ( SELECT TicketNo FROM `arlog` L where L.status NOT IN('New','Completed','Completed(Ar_aging)
','Completed(Rework)','Rework','Completed_Followup','Completed_Supervising' )
and L.assign='".$_SESSION['NAME']."' ) order by id desc") or die(mysql_error());
The query check the ticket number in arlog and displays correcly. But I want to combine TicketNo and Code in the arlog. I have made research but could not find solution. First of all is it possible?
Please try following sql:
SELECT L.TicketNo ,L.Code,C.* FROM `ar` C left join `arlog` L ON C.TicketNo = L.TicketNo where C.provider='your condition' and L.status NOT IN('New','Completed','Completed(Ar_aging)','Completed(Rework)','Rework','Completed_Followup','Completed_Supervising' ) and L.assign='your condition' order by by C.id desc
Hope this can help you!
I think you need to use CONCAT_WS()
There is a nice example of its usage in below link
MySQL SELECT AS combine two columns into one