How to select every row N times in MySql table? - mysql

I have a MySQL table like below.
ID NAME SURNAME
1 Joe Black
2 Mary Peterson
3 Bob Marley
4 Andy Murray
...
I want to write a SELECT command which will return every row N times.
Example for N = 3.
SELECT NAME, SURNAME blah-blah (3 Times ) FROM Person
NAME SURNAME
Joe Black
Joe Black
Joe Black
Mary Peterson
Mary Peterson
Mary Peterson
Bob Marley
Bob Marley
Bob Marley
Andy Murray
Andy Murray
Thank you.

You could use UNION ALL to get the result you want, but you'd better not do such job with SQL.
SELECT * FROM
(
SELECT NAME, SURNAME FROM Person
UNION ALL
SELECT NAME, SURNAME FROM Person
UNION ALL
SELECT NAME, SURNAME FROM Person
) A ORDER BY NAME

I won't suggest sql to achieve this, a much simpler way would be (assuming PHP) :
$result = $mysqli->query("SELECT NAME, SURNAME blah-blah (3 Times ) FROM Person");
while($result_set = $result->fetch_array())
{
for($i=0;$i<4;$i++)
{
echo $result_set['name']." ".$result_set['sur_name']."\n";
}
}
This would give you a better control on the result set as well as, you can have more dynamic ways of handling, how the data is displayed on the page,
for. eg, if u want a particular name to be printed only once, a simple if comparison would do, which is not possible via sql!!

SELECT NAME, SURNAME FROM Person, (SELECT * FROM Person limit 3) count_table;

The dumb manual way would be:
SELECT NAME, SURNAME FROM Person
UNION ALL
SELECT NAME, SURNAME FROM Person
UNION ALL
SELECT NAME, SURNAME FROM Person
Another way is to have a table with numbers in a single column running up to the maximum and doing a cross join with it WHERE number <= n

what about go through looping it in stored procedure like that :
delimiter //
CREATE PROCEDURE ntimes()
BEGIN
DECLARE i INT DEFAULT 0;
SET i = 0;
WHILE i < 3 DO
SELECT `Code`, `Rank` FROM Table1;
SET i = i + 1;
END WHILE;
END;
//
DELIMITER ;
Here you just change 3 to what number of repeats you want , and you dont need mass of unions .

Related

Is there a way to join tables in MS Access to get this output?

Say we have 2 tables:
Table A:
EmployeeName
Carter
Rick
Larry
Table B:
Case
Case1
Case2
Case3
Case4
Case5
Case6
Case7
Case8
Now I'd like an output like this:
EmployeeName Case
Carter Case1
Rick Case2
Larry Case3
Carter Case4
Rick Case5
Larry Case6
Carter Case7
Rick Case8
Can this be done in MS Access using SQL queries?
Yes, it can.
First, create two queries to add sequential numbers to the records:
SELECT
Employee.EmployeeName,
(Select Count(*)
From Employee As T
Where T.EmployeeName < Employee.EmployeeName) AS Id
FROM
Employee;
SELECT
Case.Case,
(Select Count(*)
From Case As T
Where T.Case < Case.Case) AS Id
FROM
Case;
Save these as qEmployee and qCase.
Then create the final query:
SELECT
qEmployee.EmployeeName,
qCase.Case
FROM
qCase,
qEmployee
WHERE
([qCase]![Id] Mod (Select Count(*) From Employee)) = [qEmployee]![Id];
Output:
If you don't want employee names to be sorted, another field to sort on must be present.

How to select column name and values both to display on a page?

I want to select a value from a row and want to display only such values where there is a value with column name
----------------
id name gender
---------------
1 Bob M
2 Anny
3 Harry M
so I want to display 2 Anny with Id and gender only, that means if I select 1 there should be id, name, gender.
I am unable to figure out how to write code statement
IF my understanding is correct, You wanted to Select the name and Gender only when you search the id? is that right?
If that so:
Please try this
SELECT id, gender FROM [your_table] WHERE id = 2
EDIT
As I have said on the comment section, Please see this as reference.
SELECT IIF(gender IS NULL , name , name & ' ' & gender) AS Info FROM [your_table]
You want to display 2 Anny with Id and gender only. concat() function will help you for this
select concat(id,' ',name) as name , gender from table_name where id=2

SQL insert both specified and selected values

I have two tables shown below:
TableOwner:
UserID Name Initials
1 Peter Pet1
2 Mary Mar1
3 Petra Pet2
TableAsset
AssetID AssetName OwnerUserID
1 Samsung 3
2 Apple 1
3 Huawei 2
Now I want to insert into TableAsset these records:
AssetID AssetName OwnerUserID
4 Doro 2
5 Sony 1
How to use insert query and select query in one step?
You can do something like this in a single query. Passing the parameter will depend on you how you do it.
insert into TableAsset(AssetName, OwnerUserID)
select 'Doro', (select UserID from TableOwner where Initials = 'Mar1')
union all
select 'Sony', (select UserID from TableOwner where Initials = 'Pet1');
THIS ANSWERS THE ORIGINAL VERSION OF THE QUESTION.
You can look them up:
insert into tableAsset(AssetName, OwnerUserID)
select #AssetName, o.UserId
from tableOwner o
where o.initials = #Initials;
This basic structure will work for any database, although the method for passing parameters may differ among databases.

MySql: How to display only 1 name only per multiple name

To make it more clear, If I have this data in MySql:
name | allowance | age
----------------------
khan | 50 | 20
aal | 60 | 22
hyme | 50 | 21
khan | 61 | 20
notice that there are two 'khan' in the database with different allowance. I want to only show the name and the age but if I show it using the mysqli select statement, there would be two 'khan' but I only want to show only 1 'khan'. How can I do it?
You need to use GROUP_CONCAT to see agges of all Khans;
select name, GROUP_CONCAT(age) ages from Table group by name
or for minimum aged khan
select name , min(age) MiniumAge from Table group by name
or for elder khan
select name , max(age) MaxAge from Table group by name
or any khan
select name , age from Table group by name
.
Please try below query:-
SELECT name, age FROM table_name WHERE group by name
If you want any from multiple same record then simply used group by query.
I think you could do this:
SELECT name, age FROM table_name WHERE group by name,age
First thing: if both those "khan"s are the same person with two different allowances then your schema is not properly normalized and it will give you big troubles later - imagine you want to change "khan" to "Khan" - now you have to update it in multiple places instead once. Depending on your actual needs you may want one table of people (person_id, name, age), and table of allowances (person_id, allowance, [..some other parameters?..]).
Second, to really get what you want, either you use group by, to get one "random" row per each name as suggested in other answers, or you can do
SELECT DISTINCT name, age FROM table;
which will give you one row per each name-age combination, so khan-20 will be there only once - but if there were khan-25 then that is probably different person and you would have two khans returned, each with their own age.
You can try this mate:
SELECT DISTINCT
name, age
FROM
<your_table>;
or this one
SELECT
name, age
FROM
<your_table>
GROUP BY
name;
Q: Is there any chance that if there are 2 records of tha same name have difference value of age? If so, kindly update the question so that better answers will be given. Cheers!

mysql query two tables

I need to query two tables like this...
table one
customers
id companyname phone
1 | microsoft | 888-888-8888
2 | yahoo | 588-555-8874
3 | google | 225-558-4421
etc...
table two
contacts
id companyid name phone
1 | 1 | sam | 558-998-5541
2 | 1 | john | 558-998-1154
3 | 3 | larry | 111-145-7885
4 | 3 | dave | 558-998-5254
5 | 2 | sam | 558-997-5421
I need to query both tables.
So if I search for sam
it should return a list of companies with the contacts
microsoft 888-888-8888
sam 558-998-5541
john 558-998-1154
yahoo 588-555-8874
sam 558-997-5421
so it returns all company with sam and all contacts with it....
same is if I would search 'microsoft' it should return without yahoo
microsoft 888-888-8888
sam 558-998-5541
john 558-998-1154
and if I search "558-998-1154" it should return like this...
microsoft 888-888-8888
sam 558-998-5541
john 558-998-1154
I hope this is clear....
Here is my current query:
SELECT * FROM
customers, customer_contacts
WHERE (customers.code LIKE '%#URL.qm1#%'
or customers.COMPANY LIKE '%#URL.qm1#%'
or customers.phone LIKE '%#URL.qm1#%'
or customers.contact LIKE '%#URL.qm1#%'
or customers.name LIKE '%#URL.qm1#%'
or customers.address1 LIKE '%#URL.qm1#%')
AND (customers.id = customer_contacts.cid
and customer_contacts.deleted = 0)
this returns only those who have a contact...
I would need
it to return the ones without contacts as well.
This is a sticky problem, one that I almost want to say "don't try to do this is one query".
I approach SQL queries like this from a programming perspective, as I feel the results tend to be less "magical". (A property I see in too many queries — it seems SQL queries these days are written using monkeys at keyboards…)
Figure out which company IDs we want to list. This is the union of these two things:
Any "people" results matched on name or number
Any "company" results matched on name or number
List out the number for that company, and the people as well.
Let's do #2 first:
SELECT
companyname AS name,
phone
FROM
customers
WHERE id IN (company_ids we want)
UNION
SELECT
name, phone
FROM
contacts
WHERE companyid IN (company_ids we want)
Since "company_ids we want" is going to be a query, rearrange this to boil it down to just 1 occurrence:
SELECT
name, phone
FROM
(
SELECT
id AS companyid,
companyname AS name,
phone
FROM
customers
UNION
SELECT companyid, name, phone FROM contacts
) AS entities
WHERE
companyid IN (company_ids we want)
Now, to fill in the fun part, we need to answer #1:
Part #1.1 is:
SELECT companyid FROM contacts WHERE name = $search OR number = $search;
Part #1.2 is:
SELECT id AS companyid FROM customers WHERE companyname = $search OR number = $search;
(Note that $search is our input — parameterized queries differ greatly from one SQL vendor to the next, so replace that syntax as needed.)
Put the UNION of those two in the IN, and we're done:
SELECT
name, phone
FROM
(
SELECT
id AS companyid,
companyname AS name,
phone
FROM
customers
UNION
SELECT companyid, name, phone FROM contacts
) AS entities
WHERE
companyid IN (
SELECT companyid FROM contacts WHERE name = $search OR phone = $search
UNION
SELECT id AS companyid FROM customers WHERE companyname = $search OR phone = $search
)
;
And pray the database can figure out a query plan that performs this in a reasonable amount of time. Sure you don't want to roundtrip to the DB a few times?
Note the methodology: We determined what we wanted ("the names/phones for customers/contacts matching certain companyids") and then figured out the missing piece ("which company ids?"). This comes from the fact that once you match a particular person in a company (say, sam), you want everyone from that company, plus the company, or everything with that company ID. Knowing that, we get our outer query (#2), and then we just need to figure out how to determine which companies we're interested in.
Note that these won't (and SQL queries, without an ORDER BY don't) give the queries back in your rather fancy order. You can add a helper column to the inner query, however, and accomplish this:
SELECT
name, phone
FROM
(
SELECT
0 AS is_person,
id AS companyid,
companyname AS name,
phone
FROM
customers
UNION
SELECT 1 AS is_person, companyid, name, phone FROM contacts
) AS entities
WHERE
companyid IN (
SELECT companyid FROM contacts WHERE name = $search OR phone = $search
UNION
SELECT id AS companyid FROM customers WHERE companyname = $search OR phone = $search
)
ORDER BY
companyid, is_person, name
;
You can also use the is_person column (if you add it to the SELECT) if you need to segment the results in whatever gets this query's results.
(And if you end up using queries of this length, please, for the love of God, -- comment them!)