How to perform a complex query using AS alias - php

First of all, I am new here and just learning sql, so bear with me.
I have a simple question. Let's say I have a table called voting with the following columns:
id, token(int), candidate(int), rank(int)
.. and I want to perform a query like:
SELECT *
FROM voting
WHERE rank > t1.rank
AND token = t1.token
.. where t1 is
SELECT rank,token
FROM voting
WHERE candidate = $mycandidate
How can I do this in a single statement using AS alias, or whatever is the simplest method?
Please note that final table created may have rows with different candidates than i have specified i.e the rank,token variables are initially chosen according to candidate but once chosen they may contain any candidate value with them.

Something like this should do, I believe:
select
v1.*
from
voting v1 inner join
voting v2
on v1.token = v2.token and
v2.candidate = $mycandidate and
v1.rank > v2.rank
EDIT changed SELECT * to SELECT v1.*

Related

SELECT statements have different number of columns

I am making a small php website in which you can follow others and then see their post.
I have three tables-
1.Posts, which has post_id and author_id
2.follow, which has following and follower
3.users, which has id, username, and all other stuff. I try the following in sql-
SELECT * FROM posts,follow,users WHERE posts.author_id=users.id AND users.id=follow.following AND follow.follower='$id' UNION SELECT * FROM posts,users WHERE posts.author_id=users.id AND users.id='$id'
Where $id is the id of the user logged in.
It displays the following error-
#1222 - The used SELECT statements have a different number of columns
I have searched for hours but I cannot find the answers to match with my query.
I will really appreciate an answer with a better version of the above code.
Thanks in advance.
Perhaps a JOIN would serve you better ... something like this:
SELECT * FROM posts
JOIN users on posts.author_id=users.id
JOIN followers on users.id=follow.following
WHERE follow.follower='$id'
When you union two queries together, the columns on both must match.
You select from posts,follow,users on the first query and posts,users on the second.
this won't work.
From the mysql manual:
The column names from the first SELECT statement are used as the column names for the results returned. Selected columns listed in corresponding positions of each SELECT statement should have the same data type

Query selected columns from two tables with a Condition clause

I have two tables-
1) ****Company_Form****
[Contract_No#,Software_Name,Company_Name,Vendor_Code]
2) ****User_Form****
[Contract_No,Invoice_No#,Invoice_Date,Invoice_Amount,Invoice_Submit_Date]
Fields denoted with # and bold are primary keys.
=>The user has to enter a software name for which he wants to get the data of.
=>I have to structure a query in which I have to display the result in the following form:
[Contract#,Software_Name,Company_Name,Invoice_No,Invoice_Date,Invoice_Submission_Date]
Now,
one Contract_No can contain many Invoice_no under its name in
the User Form table.
One Contract_No can occur one time only in
Company_Form table
The retrieved records have to be group by the latest Invoice_Date
I came to the logic that:
I have to first retrieve all the contract numbers with that software
name from Company_Form table.
I have to query that contract number from User_Form table and display
the data for each matched contract no. fetched from Company_Form
table.
The problem is that I am unable to structure a query in SQL that can do the task for me.
Kindly help me in formulating the query.
[PS] I am using SQL with PHP.
I tried a query like:
I tried one approach as :
SELECT a.ContractNo,a.SoftwareName,a.CompanyName,b.InvoiceNo,b.InvoiceDate,b.InvAmount,b.InvoiceSubmitDate
FROM Company_Form as a,User_Form as b
WHERE b.ContractNo IN(SELECT ContractNo FROM Company_Form WHERE
SoftwareName='$Sname') AND a.ContractNo=b.ContractNo;
But I am getting a error that sub query returns more than 1 row.
Can I get help from this?
I am assuming you are attempting to find the most recent price of the user selected software and its corresponding invoice. Here is an approach to do this. If this is tested to your satisfaction, I can add necessary explanation.
select uf.Contract_No#,
cf.Software_Name,
cf.Company_Name,
uf.Invoice_No#,
uf.Invoice_Date,
uf.Invoice_Amount,
uf.Invoice_Submit_Date
from User_Form uf
inner join (
-- Most recent sale of software
select Contract_No#, max(Invoice_Date)
from User_Form
group by Contract_No#
) latest
on (
-- Filter via join for latest match records
uf.Contract_No# = latest.Contract_No#
and uf.Invoice_Date = latest.Invoice_Date
)
inner join Company_Form cf
on cf.Contract_No# = uf.Contract_No#
where cf.Software_name = :software_name
If the requirement allows your sub query to return more than one row, I would suggest you to use IN instead of = in the where clause of your main query.
Please note that I have just looked at the query and have not fully understood the requirements.
Thanks.
I worked around for some time and finally came to the following query which works like a charm
SELECT a.ContractNo,a.SoftwareName,a.CompanyName,b.InvoiceNo,b.InvoiceDate,b.InvAmount,b.ISD
FROM Company_Form as a,User_Form as b
WHERE b.ContractNo IN (SELECT ContractNo FROM Company_Form WHERE SoftwareName='$Sname')
AND a.ContractNo=b.ContractNo;
If anybody needs help in understanding the logic of this query,feel free to comment below.

Return all records of non-given id if just one of those records matches the given id of another field

After searching for a damn long time, I've not found a query to make this happen.
I have an "offers" table with a "listing_id" field and a "user_id" field and I need to get ALL the records for all listing_id's where at least one record matches the given user_id.
In other words, I need a query that determines the listing_id's that the given user is involved in, and then returns all the offer records of those listing_id's regardless of user_id.
That last part is the problem. It's getting all the other user's offer records to return when I'm only providing one user's id and no listing id's
I was thinking of first determining the listing_ids in a separate query and then using a php loop to create a WHERE clause for a second query that would consist of a bunch of "listing_id = $var ||" but then I couldn't bring myself to do it because I figured there must be a better way.
Hopefully this is easy and the only reason it has escaped me is because I've had my head up my ass. Will be happy to get this one behind me.
Thanks for taking the time.
Josh
You could do two queries playing along on the MySQL side, like this:
SELECT * FROM offers WHERE listing_id IN (SELECT listing_id FROM offers WHERE user_id = 1)
If I understand what you are after you should join offers on itself on listingid match and userid = given
select * from offers AS t1
inner join offers AS t2 on t1.listingid = t2.listingid and t1.userid = 1;

Order by votes - PHP

I have a voting script which pulls out the number of votes per user.
Everything is working, except I need to now display the number of votes per user in order of number of votes. Please see my database structure:
Entries:
UserID, FirstName, LastName, EmailAddress, TelephoneNumber, Image, Status
Voting:
item, vote, nvotes
The item field contains vt_img and then the UserID, so for example: vt_img4 and both vote & nvotes display the number of votes.
Any ideas how I can relate those together and display the users in order of the most voted at the top?
Thanks
You really need to change the structure of the voting table so that you can do a normal join. I would strongly suggest adding either a pure userID column, or at the very least not making it a concat of two other columns. Based on an ID you could then easily do something like this:
select
a.userID,
a.firstName,
b.votes
from
entries a
join voting b
on a.userID=b.userID
order by
b.votes desc
The other option is to consider (if it is a one to one relationship) simply merging the data into one table which would make it even easier again.
At the moment, this really is an XY problem, you are looking for a way to join two tables that aren't meant to be joined. While there are (horrible, ghastly, terrible) ways of doing it, I think the best solution is to do a little extra work and alter your database (we can certainly help with that so you don't lose any data) and then you will be able to both do what you want right now (easily) and all those other things you will want to do in the future (that you don't know about right now) will be oh so much easier.
Edit: It seems like this is a great opportunity to use a Trigger to insert the new row for you. A MySQL trigger is an action that the database will make when a certain predefined action takes place. In this case, you want to insert a new row into a table when you insert a row into your main table. The beauty is that you can use a reference to the data in the original table to do it:
CREATE TRIGGER Entries_Trigger AFTER insert ON Entries
FOR EACH ROW BEGIN
insert into Voting values(new.UserID,0,0);
END;
This will work in the following manner - When a row is inserted into your Entries table, the database will insert the row (creating the auto_increment ID and the like) then instantly call this trigger, which will then use that newly created UserID to insert into the second table (along with some zeroes for votes and nvotes).
Your database is badly designed. It should be:
Voting:
item, user_id, vote, nvotes
Placing the item id and the user id into the same column as a concatenated string with a delimiter is just asking for trouble. This isn't scalable at all. Look up the basics on Normalization.
You could try this:
SELECT *
FROM Entries e
JOIN Voting v ON (CONCAT('vt_img', e.UserID) = v.item)
ORDER BY nvotes DESC
but please notice that this query might be quite slow due to the fact that the join field for Entries table is built at query time.
You should consider changing your database structure so that Voting contains a UserID field in order to do a direct join.
I'm figuring the Entries table is where votes are cast (you're database schema doesn't make much sense to me, seems like you could work it a little better). If the votes are actually on the Votes table and that's connected to a user, then you should have UserID field in that table too. Either way the example will help.
Lets say you add UserID to the Votes table and this is where a user's votes are stored than this would be your query
SELECT Users.id, Votes.*,
SUM(Votes.nvotes) AS user_votes
FROM Users, Votes
WHERE Users.id = Votes.UserID
GROUP BY Votes.UserID
ORDER BY user_votes
USE ORDER BY in your query --
SELECT column_name(s)
FROM table_name
ORDER BY column_name(s) ASC|DESC

getting same property from mysql with php

suppose i have 1 current user id and another user id to which current user is visiting.....than i want to fetch mysql data only if both have same options.....
for example user1 has uploaded a picture and user2 has also uploaded picture.......than how can i matchd user1 to user2 and query should be like this........
select * from users where id='user1id' or id='user2id' and imguploaded='1'
is this query is correct or not but it is not working for me..........!!
i want a working query same as above not as
select * from users where imguploaded=1
try ecapsultating your where with brackets, because of the precedence...
select * from users where (id='user1id' or id='user2id') and imguploaded='1'
if you don't mysql will presume default precedence and interpret the query like this:
select * from users where id='user1id' or (id='user2id' and imguploaded='1')
which will not give the desired result.
To check if both users have actually have a picture uploaded you could make it:
select COUNT(*) as count from users where (id='user1id' or id='user2id') and imguploaded='1'
and then check if count==2
Why would you want such a thing like this?
Anyway... create some sort of actions table where you have a structure like id, action, desc Then create a user_action table like id, user_id, action_id. Then fetch your results.
This way you store data in therefore meant tables and don't mess up userdata with their action data. This way you can also easily extend actions and compare users of their made actions.
select * from users where (id='user1id' and imguploaded='1') and (id='user2id'and imguploaded='1')
How about with a join?
query = "SELECT * FROM users AS first JOIN users AS second
ON first.imguploaded = second.imguploaded
WHERE first.userid = $user1 AND second.userid = $user2"
This query would take the two users, and if they have the same attribute (imguploaded is the same for both), return both rows, you can then select what you need. You can add more attributes to the ON clause, for example:
ON first.imguploaded = second.imguploaded OR ( first.imgdloaded = second.imgdloaded AND first.somethingelseuploaded = second.somethingelseuploaded).
This way (with the ON clause of the mysql statement) you can combine all the attributes in the AND/ON but you have to place the brackets - ( and ) - in the right places. Of course, if you don't put them, the MySQL server will just read them serially.
Is that what you need?

Categories