I am working on a little searching stuffs, the problem is that I they can choose multiple options and I want my query to be created depending of them.
Please if anybody could help me I will be so glad.
My main table of search is this:
id
name
card_id
phone_numbre
country_id
futurecountry_id
The ID is unique, the name a text, the card_id and phone_number are just ok, I can find them on my table, but the problem is when I need to go to pick up the data to the other tables, specially the country_id goes to a table named "country" where I comprare the id's to check if are the same I bring the name of the country, is the same table where I consult for get the country_id and futurecountry_id and I really have no idea what to do.
Does anybody have any idea?
p.s. Well, maybe I couldn't explain myself very good, my problem is this:
I have a form where you filled it with some data and brings you the personal information and instead the ids of the field origencountry and destinycountry I need the names, for example, if I send origencountry=10 and destinycountry=8 I will do this:
select *
from infotable,countrytable
where infotable.iddestinycountry = countrytable.id and infotable = 10
AND infotable.origencountry = countrytable.id and infotable = 8
The query seems to work fine, but it doesn't output any data.
At my table countries I have for example:
id name
1 usa
2 uk
3 spain
and at info
id name origencountry destinycountry
1 john 1 2
You can user LEFT JOIN or RIGHT JOIN.
For example :
SELECT c.country_id from country as c
LEFT JOIN futurecountry as fc ON c.country_id = fc.futurecountry_id
In this example, you return only results on country with country and futurecountry_id keys
For more informations, you can see here : http://dev.mysql.com/doc/refman/5.0/fr/join.html
Related
We have build a very simple referral system that tracks userID's without cookies and referrals for social media. I am trying to create something like a 'leader board' so I can show the UserID of the top leaders in the database.
I'm trying to combine these 2 queries into 1 query.
SELECT
Count(users.AffiliateID) AS affiliate,
users.AffiliateID
FROM
users
group by affiliateID
order by affiliate desc
This generates an output where the variable 'affiliate' contains the USERID of the top referring affiliate. In this case the #1 person is affiliateID = 5297dc41331235
What I then do is look up the name of the person with this query.
Select name from users where UserIDHash = "5297dc41331235";
How can I rewrite the query above so that it looks up the value of the name field as a column that references the value of the AffiliateID i.e. where AffiliateID=UserIDHash on each record?
Your help is greatly appreciated.
Thanks!
I have a table called LIKES as follows.
As you can see it is having two columns. UserName1, UserName2.
What this table contains is that, If one person follow other persons facebook page etc.
For example, If Jon follow bobs page then there is a entry in the table as Jon, bob, If bob follows Jon facebook page, then there is a entry called Bob, Jon.
So I want to find out all the users who are following each others profile and I want it without duplicates.
I have following query, which give results of finding users who follow each others profile. but I am not able to remove duplicates
SELECT L1.USERNAME1, L2.USERNAME2
FROM LIKES L1,
LIKES L2
WHERE L1.USERNAME1=L2.USERNAME2
AND L1.USERNAME2=L2.USERNAME1
Final output from the given table should be Jon Bob, or Bob , Jon, not the both.
my query gives the both results, How can I remove the duplicates in the resluts
First, don't use comma-style joins. That syntax has been outdated for a long time. Second, one way you can avoid duplicates in this case is to require that the first name you report in your result set occur before the first alphabetically. You can do this safely because any pair of names that will appear in your result set must appear in the source table in both orders (e.g. ("Bob", "Jon") and ("Jon", "Bob")). I am assuming here that you don't need to deal with the case of a user who follows his own page. For instance:
select *
from likes L1
where
L1.username1 < L1.username2 and
exists (select 1 from likes L2 where L1.username1 = L2.username2 and L1.username2 = L2.username1);
Result:
username1 username2
Bob Jon
Click here for a SQL fiddle that demonstrates this approach using your sample data.
It looks a little crazy, but this actually works:
select min(t.username1) as username1,
max(t.username2) as username2
from likes t
group by least(t.username1, t.username2),
greatest(t.username1, t.username2)
having count(distinct t.username1) = 2
SQLFiddle
EDIT Added the having clause to deal with my misunderstanding of OP's question
Suppose I have a table like this:
Suppose my user inputs that he wants to see all records where gender is male AND eyecolor = grey.
I already have the following SQL for that:
SELECT User, question, answer FROM [Table] WHERE User IN (
SELECT User FROM [table] WHERE (question, answer) IN (
('gender', 'male'),
('eyecolor', 'grey')
)
)
GROUP BY User
HAVING count(distinct question, answer) = 2)
However, what if my user wants to see all records for (gender = male OR gender = female) AND eyecolor = grey ? How would I format the above sql query to get it to be able to find that?
(Keep in mind, this is a searchform, so eyecolor and gender are only a few fields used for searching; I need to be able to search with and/or combo's)
I'm thinking the only way I can get this to work is something like:
SELECT User
FROM [table]
WHERE (gender = male OR gender = female) AND eyecolor = blue
And my php would have to build the query so that if the user enters more fields, the query expands with more WHERE's etc.?
I have been searching all over but have not been able to get it to work.. Admittedly I'm not the world's greatest with this.
http://sqlfiddle.com/#!2/2e112/1/0
select *
from stuff
where ID in (
select ID
from stuff
where (question='gender' and answer in ('male','female')) or
(question='eyecolor' and answer='grey')
group by ID
having count(ID)=2
)
where 2 is the number of conditions in the nested where statement. If you run that nested select on its own, it will give you just a distinct list of ID's that fit the conditions. The outer statement allows the query to return all records for the ID's that fit those conditions.
i edited this because.... i was wrong before
k... http://sqlfiddle.com/#!2/2f526/1/0
select *
from stuff
where (question='gender' and answer in ('male','female')) or
(question='eyecolor' and answer='grey') or
(question='city' and answer in ('madrid','amsterdam'))
for this query, we return one row that matches any of those conditions for any ID. only ID's that satisfy at least one of those conditions will appear in the results.
select ID, count(*) as matches
from stuff
where (question='gender' and answer in ('male','female')) or
(question='eyecolor' and answer='grey') or
(question='city' and answer in ('madrid','amsterdam'))
group by ID;
then we add the group by, so we can see how many rows are returned for each user and how many conditions they met (count(*)).
select ID
from stuff
where (question='gender' and answer in ('male','female')) or
(question='eyecolor' and answer='grey') or
(question='city' and answer in ('madrid','amsterdam'))
group by ID
having count(ID)=3;
the having count(ID)=3; is what makes this query work. we only want ID's that had 3 rows returned because we have 3 conditions.
and.... we can't use and because no row in that table will ever meet more than one of those conditions at a single time. question cannot be gender, eyecolor and city all at the same time. it has to do with your table layout. city will never be both madrid and amsterdam at the same time.... and will give us nothing. so... by using the having and an or... we can do stuff that's happy...?
and to go on a tangent.... if your table looked like this:
ID gender eyecolor city
---------------------------------------------
100 male blue madrid
200 female grey amsterdam
300 male brown somewhere
you would use and because....
select *
from table
where gender in ('male','female') and
city in ('madrid','amsterdam') and
eyecolor = 'grey'
but your table is a special one and didn't want to go that way because you really shouldn't have a column for every question... what if they change or what if you add 20? that'd be hard to maintain.
and....
select ID
from stuff
where question in ('gender','eyecolor','city') and
answer in ('male','female','grey','madrid','amsterdam')
group by ID
having count(ID)=3;
does also work but i would really be cautious with that because.. the questions and answers should stay together and be explicit because.... what if it was a dating service? and male could be an answer for a person's own gender or the gender they want to date and by doing question='gender' and answer in ('male','female') you are specifying exactly what you mean and not assuming that certain information is only a valid answer for one question.
I have 4 tables namely,
countries, states, cities, areas,
apart from countries table the rest three(states,cities,areas) contains country_id foreign key.
i wanted to return the total number of count of country_id combined in three tables for which i used jon_darstar's solution, here is the code i am using.
SELECT COUNT(DISTINCT(states.id)) + COUNT(DISTINCT(cities.id)) + COUNT(DISTINCT(areas.id))
FROM states
JOIN cities on cities.country_id = states.country_id
JOIN areas on areas.country_id = states.country_id
WHERE states.country_id IN (118);
the above code works perfectly fine although i am unable to understand the code properly, mainly the first line i.e
SELECT COUNT(DISTINCT(states.id)) + COUNT(DISTINCT(cities.id)) + COUNT(DISTINCT(areas.id))
Question 1 : doesn't that select the
primary id of the three tables
states,cities and areas and make the
count? i know this is not happening
from the result i am getting then what
is actually happening here?
However if i remove the DISTINCT from the query string it shows me a different result i.e a count of 120 whereas actually it should be 15(this is the count number of country_id in all three tables).
Question 2 : What is happening if i
use DISTINCT and remove DISTINCT?
isn't DISTINCT supposed to remove any
duplicate values. where is duplication
happening here?
thank you..
For an example, if in a country A(having primary id a.id=118),there is State B(having primary id b.id),inside that state there is City C(having primary id c.id), In city C there's Area D(having primary id d.id),E(having primary id e.id),F(f.id).lets visualize the query result in a database table.
C St Ct Ar
A->B->C->D
A->B->C->E
A->B->C->F
(Here C=Country,St=States,Ct=Cities,Ar=Areas)
Now just think what happens when you do count on above table to get total number of States within Country A without distinct.The result is 3,this way the Number of Cities is 3 and areas is 3,total 9.Because without distinct you're getting duplicate values in which you're not interested.
Now,if you use distinct count you'll get correct result cause here distinct states under
country A is 1,City is 1 and Areas is 3,total:5(excluding duplicate values)..
Hope this works!
!!Design Issue!!!
Like to add something:From your database design,i can see that you're using country id as a reference for countries from country table(to states,areas and cities) then joining states and cities then states and areas (by their country id)don't you think it's creating cross join?.Better design choice is at areas table keep foreign key of city,this way go bottom up like in city keep states and in states keep country.Or make a table for Areas where you are keeping Countries,States,Cities foreign key and areas primary key.
I am trying to understand this concept. For example: I have two tables City and Country.
Country
-------
id
abbreviation
name
City
-----
id
name
Country (name or id, or both? - This is the question)
To reference and keep a particular city in sync with the country it belongs to I guess this will be reference to country.id as a FK. This means an example of the city table will be: (200, New York, 19) - where 19 = USA in country table. But this doesn't help a person viewing the table because he wont know what 19 is without looking up in country table what 19 is.
So I want to add the country name also to city table so it reads: (200, New York, USA). I don't need the 19 to display because 19 is of no use to the reader but is only used in back to connect the tables.
So what should my tables colunms / FK look like to i can store in city table rows like this (200, New York, USA), yet ensure New york will always reference to USA in the USA lookup and keep the 19 which is the primary key for USA out of the city table so the tables look clean and easy to understand? And I assume if these are referenced, tomorrow if i update USA to be 20, it will update in the city table on its own, and same way if I rename USA to US it will update on city table on its own?
My DB is in MySQL
Why not use ISO 3166 country codes (2 character or 3 character) as the country ID? This leaves you with recognizable codes in the city table; you can map to the full name in the country table.
As for viewing the data, use a VIEW to create a good looking table:
CREATE VIEW CityInfo(CityID, CityName, CountryID, CountryName) AS
SELECT ci.id, ci.name, ci.country, co.name
FROM City AS ci JOIN Country AS co ON ci.Country = co.id;
You don't ... if you need to have "usable" tables in the DB, so someone can easily view something useful with select * etc. (or to make programing the SQL by hand easier). Then you create the tables as above, in normal form, and then create a VIEW which combines the tables.
Tables aren't supposed to be viewed by people: some application should be accessing the tables to present data to people in a way they can parse it. The reason you want to have country.id as a FK in your table is so that you don't have a million rows whose country name is "USA", because then all kinds of problems can occur, like what happens when you mistype and "US A" lands in one of the fields? Or what if you want to change what the user sees from "USA" to "United States"?
The right way to handle it is to use the country.id as you initially suggest, and then use a JOIN statement to present the data, like this:
SELECT city.name, country.name
FROM city JOIN country ON country.id = city.country
My syntax could be off, but that's in essence what you want.